How return data from an HTTP request in Swift/Objective C

前端 未结 4 1299
無奈伤痛
無奈伤痛 2021-01-15 14:41

I\'m trying to use Coinbase\'s API to get information about my online bitcoin wallet, and I\'m trying to use Swift\'s NSURLSession object to do so. Perhaps I\'m missing some

4条回答
  •  孤城傲影
    2021-01-15 15:13

    What you are asking for is a synchronous network request. There are many ways to do this, such as... NSData's init(contentsOfURL aURL: NSURL!) NSURLConnection's synchronous request method ...etc.

    These methods will block the current thread until they complete - which can be a potentially long time. Network requests can have very high timeouts, it may be several minutes before the device gives up. NSData's init with contents of URL will return NSData, not void, and does not execute asynchronously. It will block until it is complete, which is why it's recommended to not do these types of requests from the main thread. The UI will be frozen until it completes.

    In general the use of synchronous networking methods is discouraged. Asynchronous network requests are greatly preferred for a number of reasons. Using an asynchronous method that takes a completion block as a parameter will not prevent you from using the returned data elsewhere in your application. The block is executed when the network request has finished (wether it succeeds or fails) and it is passed the data, response metadata, and error. You are free to do what you want with that data - nothing prevents you from persisting it, passing it off to another object, etc. Based on your comments it sounds like you want to take the data that was the result of the network request and set it as the value of a property somewhere - that is entirely doable using an asynchronous method that uses a block as a completion handler.

提交回复
热议问题