2014-01-29 27 views
0

我最近開始在我的項目中使用NSURLConnection,我在想我用來處理接收數據的模式是否合適。NSURLConnectionDelegate調用訂單

如果我得到404或其他錯誤,我實際上不想對數據做任何事情,所以如果仍然將它附加到我的對象上將會很浪費。因此,我只想創建數據對象,一旦我獲得200狀態。

可以安全地假設-connection:didReceiveResponse:在任何-connection:didReceiveData:回調之前被調用?

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [self.data appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response 
{ 
    if (response.statusCode == 200) { 
     self.data = [NSMutableData data]; 
    } 
    else { 
     NSLog(@"Connection failed with status code %d", response.statusCode); 
     [self.connection cancel]; 
    } 
} 
+0

檢查'sendAsynchronousRequest:隊列:completionHandler:NSURLConnection'的''方法。你會愛上它的。 – Desdenova

+0

我不想使用這種方法。我需要在'-didReceiveData:'中處理小部分的數據。 –

+0

在這種情況下,yes'connection:didReceiveResponse:'是第一個被調用的。 – Desdenova

回答

1

didReceiveResponse將調用beforeDidReceiveData,並且可以得到它調用許多時間在一個連接符合蘋果的文檔

你應該爲你的委託準備接收 連接:didReceiveResponse :單個連接的多個消息多次連接;如果響應採用多部分MIME 編碼,則會發生這種情況。每次代表收到 連接:didReceiveResponse:消息時,它應該重置任何進度 指示並丟棄所有以前收到的數據(除了在多部分響應的 情況下)。

Source