使用NSInvocation在NSOperation内部进行异步NSURLConnection?

时间:2012-02-10 10:23:16

标签: objective-c ios nsurlconnection nsoperation nsinvocation

我必须在后台模式下使用NSOPeration中的Asynchrnous NSURLConnection,因为它的响应是大数据我必须避免在didEnterBackground中使用Apple的有限长度编码。而不是它我使用以下代码通过NSOperation与NSInvocation一样,但它是不工作.connectToServer正在进行NSURLConnection操作。有什么帮助吗?didReceiveData,didReceiveResponse委托方法没有被调用?

 -(void)viewDidLoad
 {
 NSOperationQueue *queue = [NSOperationQueue new];

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

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

}

 -(void)connectServer
{


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 :(得分:2)

mmmm也许您可以使用以下方法在主队列的块内进行连接:

dispatch_async(dispatch_get_main_queue(), ^{

        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0];
        _connection = [[NSURLConnection alloc] initWithRequest:request startImmediately:YES];
        [request release];
});

然后调用委托方法。

答案 1 :(得分:1)

每当您想在辅助线程上运行NSURLConnection时,您需要将该连接添加到runloops

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url 
                cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0];
    _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self
                 startImmediately:YES];
    [request release];


[_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_connection start];

    [pool release];

答案 2 :(得分:0)

我可能错了,但仍会尝试......

请参阅文档说明......适用于start方法

  

start使连接开始加载数据(如果没有)   已经

     
      
  • (void)start讨论仅当您使用此方法创建连接时,才需要调用此方法   initWithRequest:delegate:startImmediately:方法并为其提供NO   startImmediately参数。如果您不安排连接   在调用此方法之前的运行循环或操作队列中   在默认模式下,在当前运行循环中安排连接。
  •   

所以在我看来,你必须手动启动连接,因为它在一个操作队列中。 如果我错了,请纠正我。