Search code examples
iosnsurlconnectionnsoperationqueuenetworkonmainthread

iOS which thread NSURLConnection sendAsynchronousRequest runs on


I am using following code to make a network call. I know the response will be run in mainQueue as I have specified queue parameter as [NSOperationQueue mainQueue] but I am wondering where would actual sendAsynchronousRequest operation will be performed. The operation is called from mainThread so would that run asynchronously on the main thread or NSURLConnection creates background thread automatically? There is no documentation for this and iOS instrument doesn't show background threads detached so wondering how exactly this works! Apple document doesn't give details about this.

BTW I know this is deprecated but we have legacy code yet to migrate to use NSURLSession

[NSURLConnection sendAsynchronousRequest:urlRequest
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if(completion) {
                               completion(data, error);
                           }
                       }];

Same issue when you use following version;

self.urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];

Here also not sure which thread this request executes on and how to make this run asynchronously!


Solution

  • NSURLConnection uses its own internal queue. It now is a wrapper around NSURLSession, and you can find the queue (if you're interested) by looking for com.apple.NSURLSession-work in your thread list.