14

我想NSURLConnection 在后台模式下做,因为它的响应有很多数据。论坛告诉使用 Apple 的有限长度编码在didEnterBackground. 但我想避免它。而不是它,我通过 as 使用以下代码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");
    }
}
4

3 回答 3

42

这种问题被问了无数次。由于 iOS 4 操作是在辅助线程上启动的,因此不会调用委托。线程可能在调用委托之前就退出了。

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

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

编辑:更新链接。

于 2012-02-13T13:51:49.140 回答
6

Apple provides QHTTPOperation, which does just what you want, encapsulates an NSURLConnection within an NSOperation, for a single request. You can find it in Apple's sample code.

QHTTPOperation is actually a subclass of QRunLoopOperation which lets you encapsulate logic which depends on run-loop callbacks in an NSOperation.

The 3rd party ASIHTTPRequest is a similar popular solution, AFAIK it is no longer maintained though.

于 2012-02-19T21:19:06.630 回答
0

查看Apple 文档中记录的 sendAsynchronousRequest:queue:completionHandler: 方法。它允许使用 NSURLConnection 进行异步请求。

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

于 2012-02-10T06:34:04.513 回答