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:方法创建。代码如下:

/* 使用NSURLSessionDataTask加载网页数据 */
- (IBAction)loadData:(id)sender {
    // 开始加载数据,让spinner转起来
    [self.spinner startAnimating];
    
    // 创建Data Task,用于打开我的csdn blog主页
    NSURL *url = [NSURL URLWithString:@"http://blog.csdn.net/u010962810"];
    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的配置,所以只能执行简单的任务,但是对于加载数据,下载一张图片等任务已经可以应付自如。对于创建后台下载任务,支持断点续传的下载任务等将在下一篇文章中分析介绍。




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值