2012-02-10 51 views
0

我必须在背景模式下使用NSOPeration内部的异步NSURLConnection,因为它的响应具有大数据量,我必须避免苹果的有限长度编码在didEnterBackground中使用。相反,我通过NSOperation使用下面的代码和NSInvocation,但它不是working.connectToServer是否有NSURLConnection操作?请帮助吗?didReceiveData,didReceiveResponse委托方法是不是被调用?使用NSInvocation的NSOperation内的异步NSURLConnection?

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

}

+0

[异步NSURLConnection与NSOperation](http://stackoverflow.com/questions/9223537/asynchronous-nsurlconnection-with-nsoperation) – 2012-02-10 10:39:13

+0

的可能重复是connectServer方法被调用? – 2012-02-10 10:43:03

回答

0

我可能是错误的这一点,但还是西港岛线尝试...

看到文档说...为start方法

start使连接成为杜松子酒加载数据,如果它还没有 已经。

  • (无效)开始讨论调用只有当你创建一个 initWithRequest的连接这种方法是必要的:startImmediately:委托方法和 的startImmediately参数提供NO。如果您在调用此方法之前未将连接 安排在运行循环或操作队列中,则将在默认模式下的当前运行循环中调度 连接。

所以在我看来,你将不得不手动启动连接,因为它是一个操作的队列中。 纠正我,如果我错了。

+0

我试过了,它不工作..请帮忙吗? – 2012-02-10 11:41:29

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]; 
+0

我试过这种编码,它不工作..请帮忙吗? – 2012-02-10 11:41:15

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

然后委托方法应该被调用。