Does NSURLSession Take place in a separate thread?

自作多情 提交于 2019-11-30 03:21:42

问题


I was designing an app that uses NSURLSession and thinking about putting it in a different thread with Grand Central Dispatch, but if NSURLSession automatically does that in the background, I wouldn't have to use GCD then, correct?

So in other words, does NSURLSession automatically use Grand Central Dispatch in the background, so we don't have to worry about it?


回答1:


Yes,

NSURLSession does its work in a background thread. The download ALWAYS takes place on a background thread.


EDIT:

There is no reason to wrap your code that invokes NSURLSession (or URLSession in Swift 3/Swift 4) in a GCD call.


You can control whether its completion methods are executed on a background thread or not by the queue you pass in in the delegateQueue parameter to the init method. If you pass in nil, it creates a (background thread) serial operation queue where your completion methods are called. If you pass in NSOperationQueue.mainQueue() then your completion delegate methods will be invoked on the main thread and you won't have to wrap UI calls in dispatch_async() calls to the main thread.




回答2:


Here's an example of an NSURLSession request:

[[session dataTaskWithURL:[NSURL URLWithString:someURL]
      completionHandler:^(NSData *data,
                          NSURLResponse *response,
                          NSError *error) {
        // handle response

  }] resume];

From the Documentation: "This method is intended as an alternative to the sendAsynchronousRequest:queue:completionHandler: method of NSURLConnection, with the added ability to support custom authentication and cancellation." Short answer is: yes, NSURLSession will do background operations. You don't have to worry about this blocking your UI.



来源:https://stackoverflow.com/questions/30854510/does-nsurlsession-take-place-in-a-separate-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!