做過實際專案的人都知道,手機 App 的開發節奏通常是這樣的:先把介面搭出來,再從伺服器把資料拉下來填進去。與其說是「先美觀後充實」,不如說資料才是真正讓介面活起來的關鍵。
那伺服器上的資料到底是什麼形式?實務上最常見的就兩種:JSON 與 XML。近年新專案幾乎清一色走 JSON,但無論哪一種,網路傳輸的本質都一樣——全部以二進位(NSData)的形式在線上跑。
只要我們能拿到網路上的那坨二進位資料,後續就好辦:如果它是 JSON 的二進位,就用 JSON 解析器處理;如果是 XML,就交給 XML 解析器。所以整個問題被濃縮成一句話——怎麼把網路上的二進位資料取回來?
答案是一個通用的小工具類:給我一個介面網址(URL),我就能把對應的二進位檔案下載下來。下面這個 WJJHttpRequest 就是這樣誕生的,它繼承自 NSObject,內部靠 NSURLConnection 的 delegate 方法回填空資料。
#import <Foundation/Foundation.h> @interface WJJHttpRequest : NSObject // 請求的介面 @property (nonatomic, copy) NSString *httpUrl; // 網上下載回來的二進位資料 @property (nonatomic, strong) NSMutableData *data; // 回呼的代理物件 @property (nonatomic, strong) id delegate; // 回呼要觸發的 SEL @property (nonatomic, assign) SEL method; - (void)start; // 開始下載 - (void)stop; // 中斷連線 @end
#import "WJJHttpRequest.h"
#import "WJJRequestManager.h"
@interface WJJHttpRequest () <NSURLConnectionDataDelegate>
// 連線物件宣告成全域,方便 stop 時取消
@property (nonatomic, strong) NSURLConnection *connection;
@end
@implementation WJJHttpRequest
- (void)start {
NSURL *url = [NSURL URLWithString:self.httpUrl];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
// 這一行執行完,delegate 方法就會被陸續回呼,下載就此展開
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
#pragma mark - NSURLConnectionDataDelegate
// 收到伺服器回應:這時把 data 準備好(或清空重用)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (self.data == nil) {
self.data = [[NSMutableData alloc] init];
} else {
[self.data setLength:0];
}
}
// 資料是分批送來的,要持續 append
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.data appendData:data];
}
// 不管成功失敗,最後都走這裡收尾
- (void)loadFinished:(BOOL)success {
if (!success) {
[self.data setLength:0];
}
// 先確認回呼物件真的實作了我們指定的方法,再動態呼叫
if ([self.delegate respondsToSelector:self.method]) {
[self.delegate performSelector:self.method withObject:self];
}
// 把這個任務從自建的請求管理器裡移除,釋放連線
[[WJJRequestManager sharedManager] removeTask:self.httpUrl];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self loadFinished:YES];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self loadFinished:NO];
}
- (void)stop {
if (self.connection) {
[self.connection cancel];
}
self.connection = nil;
}
@end
didReceiveData: 觸發的次數是不固定的,資料會被切成好幾塊送過來,所以一定要用 appendData: 累加,而不是每次覆蓋。另外,成功與失敗最後都收斂到 loadFinished:,這樣收尾邏輯只需要寫一份,不必在兩個 delegate 裡重複處理。
用 respondsToSelector: 做檢查也是必要的防禦:萬一回呼物件沒有實作那個方法,直接 performSelector: 是會讓 App 崩潰的。
補充一句時代背景:NSURLConnection 從 iOS 9 起已被蘋果標記為 deprecated,新專案建議改用 NSURLSession(例如 NSURLSessionDataTask),但它背後的 delegate 分發模型與這裡的思路幾乎一致,理解這份程式碼對學習 NSURLSession 仍有幫助。