具有NSOperation的异步NSURLConnection

nam*_*ess 14 objective-c nsurlconnection nsoperation nsinvocation ios

我想NSURLConnection 在后台模式下做,因为它的响应有很多数据.论坛要求使用Apple的有限长度编码didEnterBackground.但我想避免使用我通过下面的代码它.相反NSOperationNSInvocation作为,但它不工作.connectToServerNSURLConnection操作.请帮忙吗?didReceiveData,didReceiveResponse委托方法不调用?

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

Nyx*_*0uf 42

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

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

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

编辑:更新链接.

  • [runLoop removePort:PORT forMode:MODE]; CFRunLoopStop(CFRunLoopGetCurrent()); (5认同)
  • 享受我辛苦赚来的50票.我应该在我的赏金之前回答:) (2认同)

Dan*_*nra 6

苹果公司提供QHTTPOperation,这是你想要正是,在封装NSURLConnection内的NSOperation,对于单个请求.您可以在Apple的示例代码中找到它.

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

第三方ASIHTTPRequest是一个类似的流行解决方案,AFAIK它不再维护.