iOS 常見的網路庫如 ASIHTTPRequest、AFNetworking、MKNetworkKit 等,底層其實都建立在 Cocoa 的 NSURLConnection 之上。ASI 停止維護後,多數專案轉向 AF,而 AF 用的正是 NSURLConnection。既然大家都靠它,不如把它本身讀清楚。
- (instancetype)initWithRequest:(NSURLRequest *)request
delegate:(id)delegate
startImmediately:(BOOL)startImmediately;
這是設計用初始化器。注意幾件事:
connectionDidFinishLoading:、connection:didFailWithError: 或 cancel 被呼叫才釋放。這一點是很多地方記憶洩漏的根源。startImmediately 傳 YES 會立刻開始下載並把 connection 加入目前的 runloop;傳 NO 則只建立連線,需要手動呼叫 start。- (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate; + (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
這兩個便捷建構子內部都是呼叫 startImmediately:YES,所以不需要再手動 start。
@property (readonly, copy) NSURLRequest *originalRequest; // 建立連線時使用的原始請求 @property (readonly, copy) NSURLRequest *currentRequest; // 連線過程中可能被改寫後的請求
currentRequest 之所以與原始請求不同,是因為正規化(canonicalization)或跟隨重新導向時,請求內容會被系統調整。
- (void)start; // 對 startImmediately:NO 建立的實例,手動啟動下載 - (void)cancel; // 取消請求並釋放 delegate
cancel 不保證代理回呼完全不會再被觸發,實務上要在 delegate 裡做好狀態檢查。
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; - (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; - (void)setDelegateQueue:(NSOperationQueue *)queue;
scheduleInRunLoop:forMode: 決定 delegate 回呼在哪個 runloop 的哪個 mode 中被觸發;setDelegateQueue: 則是把回呼派到指定的 queue 上,每次回呼等同於往 queue 加入一個 NSOperation。這兩者互斥,只能擇一設定。
// 同步請求:底層仍是非同步,只是阻塞目前執行緒等結果
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request
returningResponse:(NSURLResponse **)response
error:(NSError **)error;
// 非同步請求
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue *)queue
completionHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError))handler;
同步請求會凍結呼叫它的執行緒,因此絕對不能放在主執行緒上。非同步版本則方便省事,但只能拿到最終結果,不適合需要統計進度或串流處理的場景。
把一堆 delegate 方法收攏到一個類別裡,其他頁面用到時就不必重複實作協定:
typedef void (^NSURLConnectionCompeletionBlock)(id); @interface NSURLConnectionDelegate : NSObject <NSURLConnectionDataDelegate> @property (nonatomic, strong, readonly) NSOutputStream *os; @property (nonatomic, assign, readonly) BOOL isFinish; @property (nonatomic, strong, readonly) NSMutableData *buffer; @property (nonatomic, assign, readonly) NSUInteger contentLength; @property (nonatomic, strong) NSURLConnectionCompeletionBlock completionBlock; @end
@implementation NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *hr = (NSHTTPURLResponse *)response;
if (hr.statusCode == 200) {
_contentLength = hr.expectedContentLength;
// 也可以改寫到檔案
_os = [NSOutputStream outputStreamToMemory];
[_os open];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (!self.buffer) {
_buffer = [NSMutableData dataWithCapacity:self.contentLength];
}
[self.buffer appendData:data];
// 邊收邊寫,適合大檔案
NSUInteger totalLength = data.length;
NSUInteger totalWirte = 0;
const uint8_t *datas = data.bytes;
while (totalWirte < totalLength) {
NSInteger writeLength = [self.os write:&datas[totalWirte] maxLength:(totalLength - totalWirte)];
if (writeLength == -1) {
[connection cancel];
break;
}
totalWirte += writeLength;
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (self.completionBlock) {
self.completionBlock(error);
}
_isFinish = YES;
[self.os close];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (self.completionBlock) {
self.completionBlock([self.os propertyForKey:NSStreamDataWrittenToMemoryStreamKey]);
}
[self.os close];
_isFinish = YES;
}
@end
@interface NSURLConnectionOperation : NSOperation @property (nonatomic, strong) NSURLRequest *request; @property (nonatomic, strong) NSData *buffer; - (instancetype)initWithRequest:(NSURLRequest *)request; - (void)startAsync; @end
@implementation NSURLConnectionOperation
@synthesize executing = _executing, finished = _finished, concurrent = _concurrent;
- (void)start {
if (!self.thread) {
_thread = [NSThread currentThread];
}
self.finished = NO;
self.executing = YES;
__weak NSURLConnectionOperation *wkSelf = self;
NSURLConnectionDelegate *delegate = [NSURLConnectionDelegate new];
delegate.completionBlock = ^(id data) {
if (!wkSelf.buffer) {
wkSelf.buffer = data;
}
wkSelf.finished = YES;
wkSelf.executing = NO;
};
_connection = [[NSURLConnection alloc] initWithRequest:self.request
delegate:delegate
startImmediately:NO];
[_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_connection start];
// 自己跑 runloop,讓 delegate 回呼有機會被觸發
while (!self.isFinished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
- (void)startAsync {
_thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];
[self.thread start];
}
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
- (BOOL)isConcurrent {
return YES;
}
@end
同步請求
- (IBAction)sync:(id)sender {
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:[self request]
returningResponse:&response
error:&error];
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *hr = (NSHTTPURLResponse *)response;
if (hr.statusCode == 200) {
NSLog(@"sync response head: \n%@", hr.allHeaderFields);
self.imageView.image = [UIImage imageWithData:data];
}
}
}
自訂 Operation(可非同步執行、可併入佇列)
NSURLConnectionOperation *operation = [[NSURLConnectionOperation alloc] initWithRequest:[self request]];
__weak NSURLConnectionOperation *wkOp = operation;
operation.completionBlock = ^{
__strong NSURLConnectionOperation *sOp = wkOp; // 強引用避免中途被釋放
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = [UIImage imageWithData:sOp.buffer];
});
};
[operation start];
類方法的非同步請求
[NSURLConnection sendAsynchronousRequest:[self request]
queue:self.queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *hr = (NSHTTPURLResponse *)response;
if (hr.statusCode == 200) {
self.imageView.image = [UIImage imageWithData:data];
}
}
}];
delegate + delegateQueue
NSURLConnectionDelegate *connectionDelegate = [NSURLConnectionDelegate new];
connectionDelegate.completionBlock = ^(id data) {
if ([data isKindOfClass:[NSData class]]) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.imageView.image = [UIImage imageWithData:data];
}];
}
};
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:[self request]
delegate:connectionDelegate];
[connection setDelegateQueue:self.queue]; // delegate 回呼在該 queue 的執行緒上完成
[connection start];
讀完這輪可以發現,NSURLConnection 的設計其實很完整:同步、非同步、串流、operation 化都有對應路徑。只是它自 iOS 9 起已被 NSURLSession 取代,新專案應直接使用 NSURLSession。理解 NSURLConnection 的 delegate 生命週期與 runloop 依賴,對掌握 NSURLSession 的委派模式仍有幫助。