2012-02-10 50 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]; 
}); 

然後委託方法應該被調用。