【问题标题】:Asynchronous NSURLConnection with NSOperation使用 NSOperation 的异步 NSURLConnection
【发布时间】:2012-03-02 16:07:27
【问题描述】:

我想在后台模式下做NSURLConnection,因为它的响应有很多数据。论坛告诉使用Apple的有限长度编码在didEnterBackground中使用。 但我想避免它。而不是它,我通过NSOperationNSInvocation 使用以下代码,但它不起作用。connectToServerNSURLConnection 操作。请帮助?didReceiveData,@987654328 @delegate 方法没有被调用?

 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");
    }
}

【问题讨论】:

  • 请看我编辑的问题?

标签: objective-c ios nsurlconnection nsoperation nsinvocation


【解决方案1】:

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

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

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

编辑:更新链接。

【讨论】:

  • 享受我辛苦赚来的 50 票。你应该在我的赏金之前回答:)
  • 你能告诉我如何停止Runloop和端口吗?
  • [runLoop removePort:PORT forMode:MODE]; CFRunLoopStop(CFRunLoopGetCurrent());
  • 非常感谢@Nyx0uf,你为我节省了很多时间......!伟大的贡献!
  • 我不认为这是解决方案,答案是解决方法,但不是解决问题的方法。
【解决方案2】:

Apple 提供QHTTPOperation,它可以满足您的需求,将NSURLConnection 封装在NSOperation 中,用于单个请求。您可以在 Apple 的sample code 中找到它。

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

第 3 方 ASIHTTPRequest 是一个类似的流行解决方案,但 AFAIK 已不再维护它。

【讨论】:

    【解决方案3】:

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

    注意这需要 iOS5 或更高版本

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多