NSURLConnection在另一个线程中开始.委托方法未调用

Roo*_*Roo 5 multithreading objective-c nsurlconnection grand-central-dispatch ios

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

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

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

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data;
Run Code Online (Sandbox Code Playgroud)

在主线程上运行时一切都很好.如何在另一个线程上运行连接并获取在同一线程上调用的委托方法?

sgl*_*l0v 6

GCD隐式创建,销毁,重用线程,并且您调用的线程有可能在之后立即停止存在.这可能导致代理没有收到任何回调.

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

NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request
                                                          delegate:self
                                                  startImmediately:NO];
[connection setDelegateQueue:[[NSOperationQueue alloc] init]];
[connection start];
Run Code Online (Sandbox Code Playgroud)

通过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);
               });
Run Code Online (Sandbox Code Playgroud)