NSURLConnectionDelegate methods not called when using NSThread

五迷三道 提交于 2020-01-05 15:23:51

问题


I'm trying to run a download in a background thread as to not block the main UI thread on iOS, what I did was create a new thread using

[NSThread detachNewThreadSelector:@selector(startDownload) toTarget:downloadObject withObject:nil];

Then the following code runs on a background thread:

NSURL* urlForCalendar = [NSURL URLWithString:@"http://www.apple.com/"];

urlRequest = [NSURLRequest requestWithURL:urlForCalendar];
urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:NO];

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[urlConnection scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
[urlConnection start];

However, the delegate callbacks are never called.

EDIT: For anyone who might come across a similar problem in the future, after a bit of trying to figure out why it wasn't working, I wasn't running the loop. So the last 3 lines of code should actually be:

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];   
[urlConnection scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
[urlConnection start];
[runLoop run];

回答1:


You don't run the run loop of the thread you created, so the connection you add to the run loop is never serviced and you never get any callbacks.

Generally you just want to handle the callbacks on the main thread and then push the result to a background thread if heavy processing is required.

You can do what you're currently doing though so long as you run the run loop and tidy up properly once the download is complete.



来源:https://stackoverflow.com/questions/25023644/nsurlconnectiondelegate-methods-not-called-when-using-nsthread

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