Session Task分爲三種Data Task,Upload Task,Download Task。毫無疑問,Session Task是整個NSURLSession架構的核心目標。html
下面寫了一個簡單的Demo來初步使用下三種任務對象。這裏使用的是convenience methods,並無定製session和使用協議,都是採用completionHandler做爲回調動做。web
故事板內容爲:session
第一種Data Task用於加載數據,使用全局的shared session和dataTaskWithRequest:completionHandler:方法建立。代碼以下:架構
/* 使用NSURLSessionDataTask加載網頁數據 */ app
- (IBAction)loadData:(id)sender { url
// 開始加載數據,讓spinner轉起來 spa
[self.spinner startAnimating]; .net
// 建立Data Task,用於打開個人csdn blog主頁 3d
NSURL *url = [NSURL URLWithString:@"http://blog.csdn.net/u010962810"]; orm
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
// 輸出返回的狀態碼,請求成功的話爲200
[self showResponseCode:response];
// 在webView中加載數據
[self.webView loadData:data
MIMEType:@"text/html"
textEncodingName:@"utf-8"
baseURL:nil];
// 加載數據完畢,中止spinner
[self.spinner stopAnimating];
}];
// 使用resume方法啓動任務
[dataTask resume];
}
/* 輸出http響應的狀態碼 */
- (void)showResponseCode:(NSURLResponse *)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger responseStatusCode = [httpResponse statusCode];
NSLog(@"%d", responseStatusCode);
}
completionHandler指定任務完成後的動做。注意必定要使用resume方法啓動任務。(Upload Task和Download Task同理)
運行結果:
第二種Upload Task用於完成上傳文件任務,使用方法相似:
/* 使用NSURLSessionUploadTask上傳文件 */
- (IBAction)uploadFile:(id)sender {
// NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
// NSURLRequest *request = [NSURLRequest requestWithURL:URL];
// NSData *data = ...;
//
// NSURLSession *session = [NSURLSession sharedSession];
// NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
// fromData:data
// completionHandler:
// ^(NSData *data, NSURLResponse *response, NSError *error) {
// // ...
// }];
//
// [uploadTask resume];
}
第三種Download Task用於完成下載文件的任務,使用全局的shared session和downloadTaskWithRequest:completionHandler:方法建立。
注意:在下載任務完成後,下載的文件位於tmp目錄下,由代碼塊中的location指定(不妨輸出看看),咱們必需要在completion handler中將文件放到持久化的目錄下保存。代碼以下:
/* 使用NSURLSessionDownloadTask下載文件 */
- (IBAction)downloadFile:(id)sender {
[self.spinner startAnimating];
NSURL *URL = [NSURL URLWithString:@"http://b.hiphotos.baidu.com/image/w%3D2048/sign=6be5fc5f718da9774e2f812b8469f919/8b13632762d0f703b0faaab00afa513d2697c515.jpg"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request
completionHandler:
^(NSURL *location, NSURLResponse *response, NSError *error) {
[self showResponseCode:response];
// 輸出下載文件原來的存放目錄
NSLog(@"%@", location);
// 設置文件的存放目標路徑
NSString *documentsPath = [self getDocumentsPath];
NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL] lastPathComponent]];
// 若是該路徑下文件已經存在,就要先將其移除,在移動文件
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
[fileManager removeItemAtURL:fileURL error:NULL];
}
[fileManager moveItemAtURL:location toURL:fileURL error:NULL];
// 在webView中加載圖片文件
NSURLRequest *showImage_request = [NSURLRequest requestWithURL:fileURL];
[self.webView loadRequest:showImage_request];
[self.spinner stopAnimating];
}];
[downloadTask resume];
}
/* 獲取Documents文件夾的路徑 */
- (NSString *)getDocumentsPath {
NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = documents[0];
return documentsPath;
}
運行結果:
這個Demo中沒有爲NSURLSession指定session的delegate,因此沒有使用委託中的方法,功能比較有限,並且也沒有自行定製session的配置,因此只能執行簡單的任務,可是對於加載數據,下載一張圖片等任務已經能夠應付自如。對於建立後臺下載任務,支持斷點續傳的下載任務等將在下一篇文章中分析介紹。