您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 非同步下載:NSURLConnection 回調時序與進度追蹤

編輯:iOS 相關資訊

在 NSURLSession 普及之前,NSURLConnection 是 iOS 上做非同步網路請求的主力。理解它的回調時序,對於除錯與後續遷移到新 API 都有幫助。

一、建立連線

把請求交給 NSURLConnection,並指定一個 delegate 接收回調:

NSURL *url = [NSURL URLWithString:@"https://example.com/file"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

二、四個回調的觸發順序

整個下載過程會依序經過這幾個方法,各自負責一段工作:

1. 收到回應標頭——此時才真正開始接收 body,通常在這裡初始化用來累積資料的容器:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

2. 每收到一段資料——會被呼叫多次,把片段附加到 NSMutableData 上:

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

3. 發生錯誤——下載中斷,可在此提示使用者或安排重試:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

4. 全部完成——連線成功且資料收完,通常在這裡解析資料並釋放先前配置好的物件:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

把這四點記牢就足夠應付絕大多數情境:didReceiveResponse 負責「準備」,didReceiveData 負責「累積」,didFailWithError 與 connectionDidFinishLoading 負責「收尾」。

三、進度追蹤的做法

NSURLConnection 本身不提供進度百分比,實務上得自己算。若下載前已知檔案大小,可以在 didReceiveResponse 中取出 Content-Length,再用一個累加器比上總長度:

@property (nonatomic) long long totalBytes;
@property (nonatomic) long long receivedBytes;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    self.totalBytes = response.expectedContentLength;
    self.receivedBytes = 0;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    self.receivedBytes += data.length;
    float progress = self.totalBytes > 0 ? (float)self.receivedBytes / self.totalBytes : 0;
    // 更新進度條
}

若採用的是 ASIHTTPRequest 這類第三方庫,進度追蹤就簡單得多。每個 request 都提供了兩個 delegate:

[request setDownloadProgressDelegate:cell];   // 下載進度
[request setUploadProgressDelegate:cell];     // 上傳進度

操作的原則是:單獨執行一個請求時,直接把進度 delegate 設給該 request;若同時有多個請求、你想追蹤整批的總進度,就必須改用 ASINetworkQueue,並把進度 delegate 設在佇列上,而不是個別請求上。

四、為什麼現在該改用 NSURLSession

NSURLConnection 自 iOS 9 起已被標記為不建議使用。取而代之的 NSURLSession 在設計上更完整:支援 delegate 型與 block 型兩種回調風格、可設定背景工作階段讓 App 被終止後仍繼續下載、並透過 NSProgress 物件取得標準化的進度資訊。

對應關係大致如下:didReceiveResponse 對應 didReceiveResponse:completionHandler:,didReceiveData 對應 didReceiveData,connectionDidFinishLoading 對應 didCompleteWithError:。差別在於 NSURLSession 把「資料交付」交給 completionHandler 決定,讓你能選擇一路累積,或邊收邊寫入檔案而不必把整個檔案塞進記憶體——這對大檔下載尤其關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved