NSURLSession 是 iOS 上處理網路請求的重要工具。它支援一般請求、檔案上傳、檔案下載,也能透過後台工作階段在應用離開前景時繼續傳輸。
常見工作階段有三種:
使用 dataTask 可以取得伺服器回傳的資料,適合 API 請求與 JSON 解析。
NSString *urlString = @"https://example.com/api";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", text);
} else {
NSLog(@"%@", error.localizedDescription);
}
}];
[task resume];
上傳時常需要設定 Content-Type。若使用 multipart/form-data,要同時提供 boundary,並將檔案資料放入 request body。
NSString *urlString = @"https://example.com/upload";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
NSString *path = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"png"];
NSData *data = [NSData dataWithContentsOfFile:path];
request.HTTPBody = data;
[request setValue:@"multipart/form-data; boundary=Xia" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)data.length] forHTTPHeaderField:@"Content-Length"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
NSLog(@"上傳成功");
} else {
NSLog(@"%@", error.localizedDescription);
}
}];
[uploadTask resume];
downloadTask 下載完成後,系統會把檔案放在臨時位置。開發者需要把檔案複製或移動到正式保存路徑。
NSString *urlString = @"https://example.com/file.zip";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
if (error == nil) {
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *savePath = [cachePath stringByAppendingPathComponent:@"file.zip"];
NSURL *saveURL = [NSURL fileURLWithPath:savePath];
NSError *saveError = nil;
[[NSFileManager defaultManager] copyItemAtURL:location toURL:saveURL error:&saveError];
if (saveError == nil) {
NSLog(@"保存成功");
} else {
NSLog(@"%@", saveError.localizedDescription);
}
}
}];
[downloadTask resume];
NSURLSessionDownloadTask 提供取消、暫停與恢復方法,適合需要使用者控制下載流程的場景。
[downloadTask cancel];
[downloadTask suspend];
[downloadTask resume];
若需要即時掌握下載進度,實作 NSURLSessionDownloadDelegate 的相關方法即可。
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
// 更新進度
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
// 處理下載完成後的檔案
}
後台工作階段適合大檔案下載。即使應用被掛起,系統仍可繼續處理任務。當所有事件完成後,可透過 AppDelegate 的 completionHandler 通知系統。
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
self.backgroundSessionCompletionHandler = completionHandler;
}
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
if (self.backgroundSessionCompletionHandler != nil) {
void (^completionHandler)() = self.backgroundSessionCompletionHandler;
self.backgroundSessionCompletionHandler = nil;
completionHandler();
}
}
使用後台工作階段時,建議把 identifier 保存下來,並在需要時重新建立相同 identifier 的 session,以便接續處理未完成任務。