我在另一个线程中启动了一个 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)收不到任何回调。
如果您想在后台线程中接收回调,可以使用setDelegateQueue
或sendAsynchronousRequest: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/