Calling NSURLConnection inside dispatch_async and reading didReceiveResponse in mainRunLoop in iPhone development

元气小坏坏 提交于 2019-12-10 20:57:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/23493479/calling-nsurlconnection-inside-dispatch-async-and-reading-didreceiveresponse-in

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