0

我尝试在 NSThread 和 dispatch_queue 中使用 NSURLConnection。不调用已实现的 NSURLConnectionDelegate 方法。但是当我在 NSThread 和 NSOperationQueue 中使用 NSOperation 时,会调用这些方法。

4

2 回答 2

3

没有调用这些NSURLConnectionDelegate方法,因为您的线程或调度块在调用委托方法之前完成了执行。如果您想以NSURLConnection这种方式在自己的线程中使用,正如其他人所建议的那样,您必须保持运行循环。

是一个例子。基本上

while(!finished) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    finished = TRUE;
}

NSURLConnection综上所述,在异步块中使用同步 API不是更好吗?例如,您可以将同步请求包装在一个NSOperation

于 2012-08-28T11:25:56.877 回答
0

您可以使用基于块的方法:

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
        if ([data length] > 0 && error == nil){
            // we should check that data is OK
            NSLog(@"Data received");
        }
    }
于 2012-08-28T12:24:52.293 回答