0

我必须在后台模式下在 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");
    }
}

}

4

3 回答 3

2

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

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

然后应该调用委托方法。

于 2012-02-15T01:13:51.540 回答
1

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

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];
于 2012-02-10T11:13:10.213 回答
0

我可能对此有误,但仍会尝试...

请参阅文档说...start方法

start 使连接开始加载数据(如果尚未加载)。

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

所以在我看来,您将不得不手动启动连接,因为它位于操作队列中。如果我错了,请纠正我。

于 2012-02-10T10:50:14.930 回答