Question

What I am trying to do is getting response for following method

 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { }

after calling this

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[conn start];

inside a

dispatch_async();

But the connection method is not calling. But when I run the NSURLConnection code outside the dispatch_async it call the method.

What is the reason for that and how can I correct it? Is that because delegate refers to self and self refers the the background thread but not the UIViewController class itself?

Was it helpful?

Solution

Since you're creating a connection to be scheduled in a loop and started later, make sure to use the rendition of initWithRequest with the startImmediately parameter set to NO. Right now, you're starting the connection twice. And, more significantly, you're starting it before you scheduled it in the main run loop.

To remedy this, specify startImmediately as NO:

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[conn start];

Having said that, I see no need to dispatch this code to the background queue at all (because initWithRequest runs asynchronously and will have no discernible impact on the app performance). The only time I use the above pattern is when I'm wrapping my NSURLConnection requests in some custom NSOperation subclass (in which case, the above pattern is very useful). But in this case, it is unnecessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top