前幾天看別人的 Demo,發現請求網路資料用的是 NSURLSession,心裡納悶這是什麼、怎麼沒用過,於是查了官方文件,這才了解它是 iOS 7 才新增的網路介面,與我們熟悉的 NSURLConnection 並列。查完資料寫了個小 Demo,記錄在這裡,若有不足之處歡迎指正。
1. 建立 NSURLSessionConfiguration,用來設定 Session 的工作模式,共三種:
2. 建立 NSURLSession。有兩種寫法:一是不指定 delegate,由系統自建 queue 並以 block 回呼;二是指定 delegate 與 delegateQueue,若設為 [NSOperationQueue mainQueue] 就能在主執行緒回呼,非常省事。注意 delegate 會被強引用,因此 Session 生命週期結束後記得呼叫 invalidateAndCancel 或 finishTasksAndInvalidate。
3. 建立 Task,分三種:
#import "HMTRootViewController.h"
#import "HMTAppDelegate.h"
@interface HMTRootViewController ()
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIProgressView *progressIndicator;
@property (nonatomic, strong) NSURLSession *urlSession; // 普通會話
@property (nonatomic, strong) NSURLSessionDownloadTask *sessionDownloadTask;
@property (nonatomic, strong) NSURLSessionDownloadTask *resumableTask; // 恢復下載
@property (nonatomic, strong) NSURLSessionDownloadTask *backgroundTask; // 背景下載
@property (nonatomic, strong) NSData *partialData; // 已下載的局部資料
@end
@implementation HMTRootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, 320, 300)];
[self.view addSubview:_imageView];
self.progressIndicator = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
_progressIndicator.frame = CGRectMake(50, 500, 220, 50);
[self.view addSubview:_progressIndicator];
NSArray *titles = @[@"下載", @"上傳", @"取消", @"恢復", @"後台下載"];
NSArray *selectors = @[@"didClickDownloadButtonAction:",
@"didClickUploadButtonAction:",
@"didClickCancleButtonAction:",
@"didClickResuableButtonAction:",
@"didClickBackgroundButtonAction:"];
CGFloat startX = 20;
for (NSUInteger i = 0; i < titles.count; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(startX, 400, i == 4 ? 80 : 40, 40);
[button setTitle:titles[i] forState:UIControlStateNormal];
[button addTarget:self action:NSSelectorFromString(selectors[i])
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
startX += (i == 4 ? 90 : 50);
}
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
// 指定 delegate 與主執行緒佇列,回呼都在主執行緒
self.urlSession = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"https://www.bizhiwa.com/uploads/allimg/2012-01/22021207-1-311536.jpg"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 任務預設是掛起狀態,需呼叫 resume 才會開始
self.sessionDownloadTask = [self.urlSession downloadTaskWithRequest:request];
// 也可以用 block 寫法
// [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// }];
}
#pragma mark 點擊下載
- (void)didClickDownloadButtonAction:(UIButton *)button {
[_sessionDownloadTask resume];
}
#pragma mark 點擊上傳
- (void)didClickUploadButtonAction:(UIButton *)button {
if (_imageView.image == nil) {
NSLog(@"image view is empty");
return;
}
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGSize size = _imageView.bounds.size;
indicator.center = CGPointMake(size.width / 2.0, size.height / 2.0);
[self.imageView addSubview:indicator];
[indicator startAnimating];
NSURL *url = [NSURL URLWithString:@"https://www.bizhiwa.com/uploads/allimg/2012-01/22021207-1-311536.jpg"];
// request 預設方法是 GET,上傳要改為 PUT
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5.0f];
request.HTTPMethod = @"PUT";
// 設定身份驗證:把帳密做 BASE64 編碼,避免明文傳輸
// iOS 僅對 NSData 提供 BASE64 編碼支援
NSString *authStr = @"admin:123456";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *encodeStr = [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", encodeStr];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
NSData *imageData = UIImageJPEGRepresentation(_imageView.image, 0.75);
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:imageData
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"OK -> %@", str);
dispatch_async(dispatch_get_main_queue(), ^{
[indicator stopAnimating];
[indicator removeFromSuperview];
});
}];
[uploadTask resume];
}
#pragma mark 點擊取消
- (void)didClickCancleButtonAction:(UIButton *)button {
// NSURLConnection 一旦送出就無法取消,但 NSURLSessionTask 可以輕易取消
// 取消後會回呼 URLSession:task:didCompleteWithError:
// 若要保留續傳資訊,改用 cancelByProducingResumeData:
if (!self.sessionDownloadTask) {
[self.sessionDownloadTask cancelByProducingResumeData:^(NSData *resumeData) {
self.partialData = resumeData;
self.sessionDownloadTask = nil;
}];
}
}
#pragma mark 恢復下載(斷點續傳)
- (void)didClickResuableButtonAction:(UIButton *)button {
if (self.partialData) {
self.sessionDownloadTask = [self.urlSession downloadTaskWithResumeData:self.partialData];
self.partialData = nil;
} else {
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"https://pic4.duowan.com/wow/1002/130782267821/130782458426.jpg"]];
self.resumableTask = [self.urlSession downloadTaskWithRequest:request];
self.sessionDownloadTask = self.resumableTask;
}
[self.sessionDownloadTask resume];
}
#pragma mark 後台下載模式
- (void)didClickBackgroundButtonAction:(UIButton *)button {
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"https://dldir1.qq.com/qqfile/QQforMac/QQ_V3.1.2.dmg"]];
self.backgroundTask = [[self backgroundSession] downloadTaskWithRequest:request];
[self.backgroundTask resume];
}
#pragma mark - NSURLSessionDownloadDelegate
// 下載完成
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
// 若是背景 Session,請求結束後會呼叫 AppDelegate 的
// application:handleEventsForBackgroundURLSession:completionHandler:
// 通知你該更新 UI 了
if (session == [self backgroundSession]) {
self.backgroundTask = nil;
HMTAppDelegate *appDelegate = (HMTAppDelegate *)[UIApplication sharedApplication].delegate;
if (appDelegate.backgroundURLSessionCompletionHandler) {
void (^handler)(void) = appDelegate.backgroundURLSessionCompletionHandler;
appDelegate.backgroundURLSessionCompletionHandler = nil;
handler();
}
}
// location 是 tmp 目錄下的暫存檔,必須自行搬到家目錄
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *cachesURLPath = [[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *destinationPath = [cachesURLPath URLByAppendingPathComponent:[location lastPathComponent]];
NSError *error = nil;
BOOL success = [fileManager moveItemAtURL:location toURL:destinationPath error:&error];
[fileManager removeItemAtURL:location error:NULL];
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithContentsOfFile:[destinationPath path]];
self.imageView.image = image;
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
});
}
}
// 無論成功與否,完成後都會回呼
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
// error 為 nil 代表成功;否則可從中查詢失敗原因
// 若下載了一部分,error 會包含 NSData,可用於後續續傳
if (error == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
self.progressIndicator.hidden = YES;
});
}
}
// 傳輸進度
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
double currentValue = totalBytesWritten / (double)totalBytesExpectedToWrite;
dispatch_async(dispatch_get_main_queue(), ^{
self.progressIndicator.hidden = NO;
self.progressIndicator.progress = currentValue;
});
}
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
}
#pragma mark - 背景 Session
// 即使 App 不在前景,仍可繼續傳輸;前提是會話模式設為 background
- (NSURLSession *)backgroundSession {
// 同一個 identifier 只能建立一個背景 Session,故用 dispatch_once
static NSURLSession *backgroundSession = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration backgroundSessionConfiguration:@"com.shinobicontrols.BackgroundDownload.BackgroundSession"];
backgroundSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
});
return backgroundSession;
}
@end
typedef void (^MyBlock)(void);
@property (copy, nonatomic) MyBlock backgroundURLSessionCompletionHandler;
- (void)application:(UIApplication *)application
handleEventsForBackgroundURLSession:(NSString *)identifier
completionHandler:(void (^)())completionHandler {
self.backgroundURLSessionCompletionHandler = completionHandler;
}
除了支援背景傳輸,NSURLSession 也把「資料接收」與「檔案下載」拆成了兩種不同的 task。下載任務由系統直接寫入暫存檔,不必把整個回應我先囤在記憶體裡,處理大檔案時記憶體用量差異明顯。此外,每個 task 都可以獨立取消、暫停、恢復,這是 NSURLConnection 做不到的。
需要補充的是,NSURLConnection 在 iOS 9 已被正式廢棄,新的專案請一律採用 NSURLSession。若只是簡單的請求,現在更常見的做法是搭配 AFNetworking 或 Alamofire,它們在 Session 之上又封裝了序列化、重試與進度回呼等便利功能。