NSURLSession

NSURLSession

  • 使用步骤
    • 创建NSURLSession
    • 创建Task
    • 执行Task

NSURLSessionDataTask

  • GET
复制代码
 1 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];
 2     NSURLRequest *request = [NSURLRequest requestWithURL:url];
 3 
 4     // 1.获得NSURLSession对象
 5     NSURLSession *session = [NSURLSession sharedSession];
 6 
 7     // 2.创建任务
 8     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
 9         NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
10     }];
11 
12     // 3.启动任务
13     [task resume];
14     NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];
15     // 1.获得NSURLSession对象
16     NSURLSession *session = [NSURLSession sharedSession];
17 
18     // 2.创建任务
19     NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
20          NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
21     }];
22     // 3.启动任务
23     [task resume];
复制代码

 

  • POST
复制代码
 1 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
 2     // 设置请求头
 3     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 4     request.HTTPMethod = @"POST";
 5     request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
 6 
 7     // 1.获得NSURLSession对象
 8     NSURLSession *session = [NSURLSession sharedSession];
 9 
10     // 2.创建任务
11     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
12         NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
13     }];
14     // 3.启动任务
15     [task resume];
复制代码

 

  • NSURLSessionDataDelegate代理注意事项
    • Task都是通过Session监听
      // 1.获得NSURLSession对象
      NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

       

    • NSURLSessionDataDelegate默认不会接受数据
复制代码
 1 /**
 2  * 1.接收到服务器的响应
 3  */
 4 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
 5 {
 6     NSLog(@"%s", __func__);
 7     NSLog(@"%@", [NSThread currentThread]);
 8     /*
 9      NSURLSessionResponseAllow: 去向处理服务器响应, 内部会调用[task cancle]
10      NSURLSessionResponseCancel: 允许处理服务器的响应,才会继续接收服务器返回的数据
11      NSURLSessionResponseBecomeDownload: 讲解当前请求变为下载
12      */
13     completionHandler(NSURLSessionResponseAllow);
14 }
15 /**
16  * 2.接收到服务器的数据(可能会被调用多次)
17  */
18 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
19 {
20     NSLog(@"%s", __func__);
21 }
22 /**
23  * 3.请求成功或者失败(如果失败,error有值)
24  */
25 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
26 {
27     NSLog(@"%s", __func__);
28 }
复制代码

 


NSURLSessionDownloadTask

  • DownloadTask默认已经实现边下载边写入

    复制代码
     1 // 1.创建request
     2   NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
     3   NSURLRequest *request = [NSURLRequest requestWithURL:url];
     4 
     5   // 2.创建session
     6   NSURLSession *session = [NSURLSession sharedSession];
     7 
     8   // 3.创建下载任务
     9   NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    10       NSLog(@"%@", location.absoluteString);
    11 
    12       NSFileManager *manager = [NSFileManager defaultManager];
    13       NSString *toPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    14       toPath = [toPath stringByAppendingPathComponent:response.suggestedFilename];
    15       // 将下载好的文件从location移动到cache
    16       [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:toPath] error:nil];
    17   }];
    18 
    19   // 4.开启下载任务
    20   [task resume];
    复制代码

     

  • DownloadTask断点下载

    • 暂停: suspend
    • 继续: resume
    • 取消: cancel
      • 任务一旦被取消就无法恢复
    • 区别并返回下载信息

      复制代码
      1 //取消并获取当前下载信息
      2 [self.task cancelByProducingResumeData:^(NSData *resumeData) {
      3   self.resumeData = resumeData;
      4 }];
      5 
      6 // 根据用户上次的下载信息重新创建任务
      7 self.task = [self.session downloadTaskWithResumeData:self.resumeData];
      8 [self.task resume];
      复制代码

       

  • DownloadTask监听下载进度

复制代码
 1 /**
 2  * 每当写入数据到临时文件时,就会调用一次这个方法
 3  * totalBytesExpectedToWrite:总大小
 4  * totalBytesWritten: 已经写入的大小
 5  * bytesWritten: 这次写入多少
 6  */
 7 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
 8 {
 9     NSLog(@"正在下载: %.2f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
10 }
11 
12 /*
13  * 根据resumeData恢复任务时调用
14  * expectedTotalBytes:总大小
15  * fileOffset: 已经写入的大小
16  */
17 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
18 {
19     NSLog(@"didResumeAtOffset fileOffset = %lld , expectedTotalBytes = %lld", fileOffset, expectedTotalBytes);
20 }
21 /**
22  * 下载完毕就会调用一次这个方法
23  */
24 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
25 {
26     NSLog(@"下载完毕");
27     // 文件将来存放的真实路径
28     NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
29 
30     // 剪切location的临时文件到真实路径
31     NSFileManager *mgr = [NSFileManager defaultManager];
32     [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
33 }
34 /**
35  * 任务完成
36  */
37 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
38 {
39     NSLog(@"didCompleteWithError");
40 }
复制代码

 


离线断点下载

  • 使用NSURLSessionDataTask
复制代码
1 NSMutableURLRequest *reuqest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
2 // 核心方法, 实现从指定位置开始下载
3 NSInteger currentBytes = KCurrentBytes;
4 NSString *range = [NSString stringWithFormat:@"bytes=%zd-", currentBytes];
5 [reuqest setValue:range forHTTPHeaderField:@"Range"];
6 
7 // 核心方法, 自己实现边下载边写入
8 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data;
复制代码

 


NSURLSessionUploadTask

  • 设置设置请求头, 告诉服务器是文件上传
    • multipart/form-data; boundary=lnj
  • 必须自己严格按照格式拼接请求体
  • 请求体不能设置给request, 只能设置给fromData

    • The body stream and body data in this request object are ignored. +
      [[self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
      }] resume];

       

      注意:以下方法用于PUT请求
[self.session uploadTaskWithRequest:<#(nonnull NSURLRequest *)#> fromFile:<#(nonnull NSURL *)#>]

 

  • 监听上传进度
复制代码
 1 /*
 2  bytesSent: 当前发送的文件大小
 3  totalBytesSent: 已经发送的文件总大小
 4  totalBytesExpectedToSend: 需要发送的文件大小
 5  */
 6 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
 7 {
 8     NSLog(@"%zd, %zd, %zd", bytesSent, totalBytesSent, totalBytesExpectedToSend);
 9 }
10 
11 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
12 {
13     NSLog(@"%s", __func__);
14 }
15  
复制代码

 

断点下载:

   

断点下载头设置:

    

复制代码
 1 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_02.mp4"];
 2 
 3         NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 4 
 5         // 设置请求头
 6 
 7         
 8 
 9         NSUInteger cur = [[[NSFileManager defaultManager] attributesOfItemAtPath:_path error:nil][NSFileSize] integerValue];
10 
11         NSString *range = [NSString stringWithFormat:@"bytes:%zd-", cur];
12 
13         [request setValue:range forHTTPHeaderField:@"Range"];
14 
15         
16 
17         _task = [self.session dataTaskWithRequest:request];
复制代码

文件上传格式拼接:

复制代码
 1 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
 2 
 3     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 4 
 5     
 6 
 7     // 1.设置请求头
 8 
 9     request.HTTPMethod = @"POST";
10 
11     [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", XMGBoundary] forHTTPHeaderField:@"Content-Type"];
12 
13  
14 
15     // 2.拼接请求体
16 
17     NSMutableData *body = [NSMutableData data];
18 
19     // 文件参数
20 
21     // 分割线
22 
23     [body appendData:XMGEncode(@"--")];
24 
25     [body appendData:XMGEncode(XMGBoundary)];
26 
27     [body appendData:XMGNewLine];
28 
29     
30 
31     // 文件参数名
32 
33     [body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
34 
35     [body appendData:XMGNewLine];
36 
37     
38 
39     // 文件的类型
40 
41     [body appendData:XMGEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
42 
43     [body appendData:XMGNewLine];
44 
45     
46 
47     // 文件数据
48 
49     [body appendData:XMGNewLine];
50 
51     [body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/课堂共享/视屏/02-NSURLSession基本使用.mp4"]];
52 
53     [body appendData:XMGNewLine];
54 
55     
56 
57     // 结束标记
58 
59     /*
60 
61      --分割线--\r\n
62 
63      */
64 
65     [body appendData:XMGEncode(@"--")];
66 
67     [body appendData:XMGEncode(XMGBoundary)];
68 
69     [body appendData:XMGEncode(@"--")];
70 
71     [body appendData:XMGNewLine];
复制代码

 

posted @ 2015-08-24 22:27  Apolla  阅读(370)  评论(0编辑  收藏  举报