具有NSOperation的异步NSURLConnection

时间:2012-02-10 06:14:07

标签: objective-c ios nsurlconnection nsoperation nsinvocation

我想在后台模式下执行NSURLConnection,因为它的响应有很多数据。论坛要求使用Apple的有限长度编码在didEnterBackground中使用。 但是我想避免它。而不是它。我使用NSOperationNSInvocation使用以下代码,但它不起作用。connectToServer正在进行NSURLConnection操作。请问didReceiveDatadidReceiveResponse委托方法不会被调用吗?

 NSOperationQueue *queue = [NSOperationQueue new];

NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                        selector:@selector(connectToServer)
                                                                          object:nil];

[queue addOperation:operation];
[operation release];
[queue autorelease];

 -(void)connectToServer
{
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *theConnection = [[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] autorelease];

    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
}

3 个答案:

答案 0 :(得分:42)

这个问题被问了很多次。代理没有被调用,因为从iOS 4开始,操作是在辅助线程上启动的。线程可能会在代理被调用之前退出。

保持主线程的连接,并使用GCD在后台线程中处理数据。

我在这里写了所有这些内容:http://cocoaintheshell.com/2011/04/nsurlconnection-synchronous-asynchronous/

编辑:更新了链接。

答案 1 :(得分:6)

Apple提供QHTTPOperation,它可以满足您的需求,在NSURLConnection内为NSOperation封装一个请求。您可以在Apple的sample code

中找到它

QHTTPOperation实际上是QRunLoopOperation的子类,它允许您封装依赖于NSOperation中的运行循环回调的逻辑。

第三方ASIHTTPRequest是一种类似的流行解决方案,AFAIK不再保留它。

答案 2 :(得分:0)

查看sendAsynchronousRequest:queue:completionHandler:方法记录here in Apple's Documentation。它允许使用NSURLConnection进行异步请求。

请注意,这需要iOS5或更高版本