您的位置:首页 > 其它

NSURLSession学习笔记(二)Session Task

2016-05-17 09:07 162 查看
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





/* 使用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用于完成上传文件任务,使用方法类似:

[objc] view
plaincopy





/* 使用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中将文件放到持久化的目录下保存。代码如下:

[objc] view
plaincopy





/* 使用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的配置,所以只能执行简单的任务,但是对于加载数据,下载一张图片等任务已经可以应付自如。对于创建后台下载任务,支持断点续传的下载任务等将在下一篇文章中分析介绍。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: