• NSURLSession学习笔记(二)Session Task


    Session Task分为三种Data Task,Upload Task,Download Task。毫无疑问,Session Task是整个NSURLSession架构的核心目标。

    下面写了一个简单的Demo来初步使用下三种任务对象。这里使用的是convenience methods,并没有定制session和使用协议,都是采用completionHandler作为回调动作。


    故事板内容为:

    第一种Data Task用于加载数据,使用全局的shared session和dataTaskWithRequest:completionHandler:方法创建。代码如下:

    [objc] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. /* 使用NSURLSessionDataTask加载网页数据 */  
    2. - (IBAction)loadData:(id)sender {  
    3.     // 开始加载数据,让spinner转起来  
    4.     [self.spinner startAnimating];  
    5.       
    6.     // 创建Data Task,用于打开我的csdn blog主页  
    7.     NSURL *url = [NSURL URLWithString:@"http://blog.csdn.net/u010962810"];  
    8.     NSURLRequest *request = [NSURLRequest requestWithURL:url];  
    9.     NSURLSession *session = [NSURLSession sharedSession];  
    10.     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request  
    11.                                                 completionHandler:  
    12.                                       ^(NSData *data, NSURLResponse *response, NSError *error) {  
    13.                                           // 输出返回的状态码,请求成功的话为200  
    14.                                           [self showResponseCode:response];  
    15.                                             
    16.                                           // 在webView中加载数据  
    17.                                           [self.webView loadData:data  
    18.                                                         MIMEType:@"text/html"  
    19.                                                 textEncodingName:@"utf-8"  
    20.                                                          baseURL:nil];  
    21.                                             
    22.                                           // 加载数据完毕,停止spinner  
    23.                                           [self.spinner stopAnimating];  
    24.                                       }];  
    25.     // 使用resume方法启动任务  
    26.     [dataTask resume];  
    27. }  
    28.   
    29. /* 输出http响应的状态码 */  
    30. - (void)showResponseCode:(NSURLResponse *)response {  
    31.     NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;  
    32.     NSInteger responseStatusCode = [httpResponse statusCode];  
    33.     NSLog(@"%d", responseStatusCode);  
    34. }  

    completionHandler指定任务完成后的动作。注意一定要使用resume方法启动任务。(Upload Task和Download Task同理)

    运行结果:

    第二种Upload Task用于完成上传文件任务,使用方法类似:

    [objc] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. /* 使用NSURLSessionUploadTask上传文件 */  
    2. - (IBAction)uploadFile:(id)sender {  
    3. //    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];  
    4. //    NSURLRequest *request = [NSURLRequest requestWithURL:URL];  
    5. //    NSData *data = ...;  
    6. //      
    7. //    NSURLSession *session = [NSURLSession sharedSession];  
    8. //    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request  
    9. //                                                               fromData:data  
    10. //                                                      completionHandler:  
    11. //                                          ^(NSData *data, NSURLResponse *response, NSError *error) {  
    12. //                                              // ...  
    13. //                                          }];  
    14. //      
    15. //    [uploadTask resume];  
    16. }  



    第三种Download Task用于完成下载文件的任务,使用全局的shared session和downloadTaskWithRequest:completionHandler:方法创建。

    注意:在下载任务完成后,下载的文件位于tmp目录下,由代码块中的location指定(不妨输出看看),我们必须要在completion handler中将文件放到持久化的目录下保存。代码如下:

    [objc] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. /* 使用NSURLSessionDownloadTask下载文件 */  
    2. - (IBAction)downloadFile:(id)sender {  
    3.     [self.spinner startAnimating];  
    4.       
    5.     NSURL *URL = [NSURL URLWithString:@"http://b.hiphotos.baidu.com/image/w%3D2048/sign=6be5fc5f718da9774e2f812b8469f919/8b13632762d0f703b0faaab00afa513d2697c515.jpg"];  
    6.     NSURLRequest *request = [NSURLRequest requestWithURL:URL];  
    7.     NSURLSession *session = [NSURLSession sharedSession];  
    8.     NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request  
    9.                                                             completionHandler:  
    10.                                               ^(NSURL *location, NSURLResponse *response, NSError *error) {  
    11.                                                   [self showResponseCode:response];  
    12.                                                     
    13.                                                   // 输出下载文件原来的存放目录  
    14.                                                   NSLog(@"%@", location);  
    15.                                                     
    16.                                                   // 设置文件的存放目标路径  
    17.                                                   NSString *documentsPath = [self getDocumentsPath];  
    18.                                                   NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];  
    19.                                                   NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[response URL] lastPathComponent]];  
    20.                                                     
    21.                                                   // 如果该路径下文件已经存在,就要先将其移除,在移动文件  
    22.                                                   NSFileManager *fileManager = [NSFileManager defaultManager];  
    23.                                                   if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {  
    24.                                                       [fileManager removeItemAtURL:fileURL error:NULL];  
    25.                                                   }  
    26.                                                   [fileManager moveItemAtURL:location toURL:fileURL error:NULL];  
    27.                                                     
    28.                                                   // 在webView中加载图片文件  
    29.                                                   NSURLRequest *showImage_request = [NSURLRequest requestWithURL:fileURL];  
    30.                                                   [self.webView loadRequest:showImage_request];  
    31.                                                     
    32.                                                   [self.spinner stopAnimating];  
    33.                                               }];  
    34.       
    35.     [downloadTask resume];  
    36. }  
    37.   
    38. /* 获取Documents文件夹的路径 */  
    39. - (NSString *)getDocumentsPath {  
    40.     NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
    41.     NSString *documentsPath = documents[0];  
    42.     return documentsPath;  
    43. }  


    运行结果:

    这个Demo中没有为NSURLSession指定session的delegate,所以没有使用委托中的方法,功能比较有限,而且也没有自行定制session的配置,所以只能执行简单的任务,但是对于加载数据,下载一张图片等任务已经可以应付自如。对于创建后台下载任务,支持断点续传的下载任务等将在下一篇文章中分析介绍。

  • 相关阅读:
    Linux搭建iscsi服务,客户端(Linux&Win XP)挂载使用
    SecucreCRT安装与破解
    最全的HCIA-R&S实验笔记
    AtCoder Grand Contest 036
    Comet OJ CCPC-Wannafly & Comet OJ 夏季欢乐赛(2019)
    2019慈溪集训小记
    Codeforces Round #573 (Div. 1)
    Comet OJ
    Codeforces Round #576 (Div. 1)
    Codechef August Challenge 2019 Division 2
  • 原文地址:https://www.cnblogs.com/hanzhuzi/p/4069641.html
Copyright © 2020-2023  润新知