相較於 block 回呼,delegate 模式的優勢在於「可以分段處理」。網路資料並不是一次到齊的,系統會分很多批送來。用 delegate 你可以在收到 response 時先建立容器、每收到一批就 append、全部收完才做解析,也能即時掌握進度顯示下載百分比。大檔案下載時這個模式特別有用。
- (IBAction)DelegateButtonDidClicked:(UIButton *)sender {
NSString *urlString = @"https://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 需遵循 NSURLConnectionDataDelegate 協議
[NSURLConnection connectionWithRequest:request delegate:self];
}
這個方法在整個請求生命週期中只會被呼叫一次,最合適的用途就是初始化接收用的容器。順帶一提,response 物件裡有 expectedContentLength,可以拿來算進度。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.receiveData = [NSMutableData data];
}
data 分批送來,每一批都要 append 到容器上,不能覆蓋。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.receiveData appendData:data];
}
這才是做解析的時機。此時 receiveData 才是完整的回應內容。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.receiveData
options:NSJSONReadingMutableContainers error:nil];
NSArray *array = dict[@"news"];
self.newsArray = [NSMutableArray array];
for (NSDictionary *smallDict in array) {
NewsModal *modal = [[NewsModal alloc] init];
[modal setValuesForKeysWithDictionary:smallDict];
[self.newsArray addObject:modal];
}
for (NewsModal *modal in self.newsArray) {
NSLog(@"%@", modal.title);
}
}
一定要實作這個方法。少了它,網路異常時 App 會安靜地什麼都不做,使用者只會看到一個永遠轉圈的畫面。
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"%@", error);
// 此處應給使用者提示或提供重試機制
}
NSURLConnection 已於 iOS 9 廢棄,但 delegate 的概念在 NSURLSession 中完全保留,只是換成 NSURLSessionDataDelegate:
// 收到響應(可回傳 completionHandler 繼續接收)
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
completionHandler(NSURLSessionResponseAllow);
}
// 分批接收
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data { }
// 完成或失敗(兩者合一)
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error { }
概念一一對應,只是把「完成」與「失敗」合併進同一個方法,並多了一個 error 是否為 nil 的判斷。