ios - NSURLConnection 在另一个线程中启动。未调用委托(delegate)方法

标签 ios objective-c multithreading nsurlconnection grand-central-dispatch

我在另一个线程中启动了一个 NSURLConnection:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
        ^{
            NSURLConnection *connection = [NSURLConnection connectionWithRequest:[request preparedURLRequest] delegate:self];
            [connection start];
         });

但是我的委托(delegate)方法没有被调用:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data;

在主线程上运行时一切正常。如何在另一个线程上运行连接并在同一线程上调用委托(delegate)方法?

最佳答案

GCD 隐式地创建、销毁、重用线程,您调用 start 的线程有可能会在之后立即停止存在。这可能会导致委托(delegate)收不到任何回调。

如果您想在后台线程中接收回调,可以使用setDelegateQueuesendAsynchronousRequest:queue:completionHandler: 方法:

NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request
                                                          delegate:self
                                                  startImmediately:NO];
[connection setDelegateQueue:[[NSOperationQueue alloc] init]];
[connection start];

通过 GCD 在后台线程中启动 NSURLConnection 的最简单方法是:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
               ^{
                   NSURLResponse* response = nil;
                   NSError* error = nil;
                   [NSURLConnection sendSynchronousRequest:request] returningResponse:&response error:&error];
                   NSLog(@"%@", response);
               });

关于ios - NSURLConnection 在另一个线程中启动。未调用委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32147035/

相关文章:

multithreading - Qt + OpenCV - 在 QLabel 上显示图像

java - 我应该在多线程程序中使用连接池吗?

java - libGDX iOS 应用程序在调用 creat() 后崩溃

ios - UITableViewController 不显示自定义原型(prototype)单元格

ios - 想要像 Pinterest 一样制作详细 View

ios - 在collectionView中加载图像

ios - 数据值溢出

ios - Sprite Kit 通用应用程序 : Same textures for iPhone and non-retina iPad?

ios - CoreData 对象未在屏幕之间保存

c++ - 在消费者循环中重用 unique_lock