在非主线程运行NSURLConnection

说明:不推荐在非主线程使用NSURLConnection。

确实想要 在其他线程运行的话,解决方案如下:

The problem arises from the background thread stopping before the NSURLConnection actually gets any response. Luckily it's pretty easy to force a thread/run loop to keep running with CFRunLoopRun(). Just don't forget to stop it when you're done with CFRunLoopStop(CFRunLoopGetCurrent()).

- (void)startLoadWithURL:(NSURL *)url {
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
    CFRunLoopRun();
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // Do something with the finished connection
    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Handle the error
    CFRunLoopStop(CFRunLoopGetCurrent());
}


你可能感兴趣的:(thread,url)