下載是每個 App 都會做的事,重點在於「不要卡住使用者」。NSURLConnection 的非同步模式透過四個 delegate 方法把流程拆開,理解每個方法的時機,就能把資料正確拼起來。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
把這四點串起來就是一個完整的非同步下載:在 response 建容器、在 data 累加、在 finish 收割、在 fail 善後。
每個 ASIHTTPRequest 都有兩個 delegate 可以追進度:
downLoadProgressDelegate:下載進度,例如 [request setDownloadProgressDelegate:cell];upLoadProgressDelegate:上傳進度使用上有個界線要記住:若只跑單一個 request,直接為該 request 設定進度 delegate 即可;若要追蹤整批佇列的整體進度,則必須改用 ASINetworkQueue,並把進度 delegate 設在 queue 上。
補充:NSURLConnection 已被 NSURLSession 取代,新專案請用 NSURLSessionDownloadTask 搭配 progress 屬性(或 URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)來追進度;ASIHTTPRequest 系列則早已停止維護。