2012-03-01 112 views
0

當我使用NSURLConnection時如何使完整的數據?我怎樣才能使用NSURLConnection時完整的數據

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
} 

的NSData的粘貼部位? 我應該做什麼清楚我想從URL地址下載文件到我的文檔目錄,我想知道有多少字節已經下載完成什麼是最好的方式?

回答

2

創建一個NSMutableData並在接收數據時附加它。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    if (responseData == nil) { 
     responseData = [[NSMutableData data] retain]; 
    } 
    [responseData appendData:data]; 
} 

或者

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    responseData = [[NSMutableData data] retain]; 
} 

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

然後與數據處理的connectionDidFinishLoading

記住,一旦你完成它釋放的數據和連接。

對於您可以參照該文件更詳細:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

+0

是什麼responseData? – mamrezo 2012-03-01 07:42:10

+0

我更新了我的答案,responseData是NSMutableData的一個實例 – Hanon 2012-03-01 07:44:47