iOS 7 之後蘋果推出了 NSURLSession,但為了向下相容 iOS 6,專案裡還是常常看到 NSURLConnection 的身影。它雖然已被標記為不建議使用,但理解它的運作方式,對看懂老專案或除錯仍有幫助。
這種方式會分多次回傳資料,需要自己用 NSMutableData 把片段一塊塊接起來,全部收完才由 connectionDidFinishLoading: 通知。
@interface ViewController () <NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSMutableData *receivedData;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
_receivedData = [NSMutableData data];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
NSLog(@"Downloading...");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Finished");
}
@end
如果只需要「把整包資料拿回來」,用 Block 版本就輕鬆多了,不用自己管理暫存緩衝區:
[NSURLConnection sendAsynchronousRequest:theRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"Finished");
}];
Delegate 方式的優勢是可以邊收邊處理,適合大檔案下載、串流、需要回報進度的情境;Block 方式適合小請求、一次性拉取 JSON 或 XML 這類場景,程式碼量最少。
不過在真實專案中,建議直接改用 NSURLSession:它支援背景傳輸、可暫停與恢復的工作,並以 delegate 或 completion handler 兩種形態同時滿足上述需求,是目前的標準做法。