说明:不推荐在非主线程使用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());
}
本文介绍了在非主线程中使用NSURLConnection时遇到的问题及解决方法。为避免因背景线程提前停止导致连接未获取到响应的情况,文章提供了一种通过CFRunLoopRun()强制线程/运行循环继续运行的方案,并展示了如何在请求完成或失败时停止循环。
2735

被折叠的 条评论
为什么被折叠?



