iOS边练边学--NSURLSession、NSURLSessionTask的介绍与使用以及url中包含了中文的处理方法

转载自:iOS边练边学--NSURLSession、NSURLSessionTask的介绍与使用以及url中包含了中文的处理方法

一、NSURLSession、NSURLSessionTask的使用步骤

首先创建NSURLSession对象
通过NSURLSession对象创建对应的任务

11111.png

1.NSURLSessionDataTask的GET和POST -- 以及url中包含了中文的解决办法

image
image

2.NSURLSessionDownloadTask实现小文件的下载

image

3.NSURLSessionDownloadTask实现大文件的断点下载 -- 暂时没有实现退出程序后的文件续传

 #import "ViewController.h"
// 最好是用到哪个任务就实现哪种任务类型的代理协议
@interface ViewController () <NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
@property (weak, nonatomic) IBOutlet UILabel *precentLabel;
 
 /** task */
@property(nonatomic,strong) NSURLSessionDownloadTask *task;

 /** resumeData */
@property(nonatomic,strong) NSData *resumeData;
  
 /** session */
@property(nonatomic,strong) NSURLSession *session;
  
@end
  
 @implementation ViewController 19 
  - (NSURLSession *)session
  {
      if (_session == nil) { 23         // 通过设置NSURLSession的Configuration来指定session的代理,以及代理的线程
          _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
      }
      return _session; 27 }
  
  - (IBAction)start:(id)sender {
      
      NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4"]];
      // 只通过request创建task  文件的具体下载通过代理来实现,
      self.task = [self.session downloadTaskWithRequest:request];      
      [self.task resume];
      
  }
  - (IBAction)pause:(id)sender {
      // 取消任务 并产生一个恢复数据 -- 任务一旦取消就不能恢复
      [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) { 
         // 将恢复数据存入变量
          self.resumeData = resumeData; 
     }];
      
  }
  - (IBAction)goOn:(id)sender {
      
      // 任务已经被取消了,只能重新开启任务,通过resumeData继续下载任务
      self.task = [self.session downloadTaskWithResumeData:self.resumeData]; 50     
      // 恢复任务
      [self.task resume];
  }
  
  - (void)viewDidLoad {
      [super viewDidLoad];
      // Do any additional setup after loading the view, typically from a nib.
  }
  
  - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {      
  }
  
  #pragma mark - <NSURLSessionDownloadDelegate>
 
  - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  {
      // bytesWritten -- 本次写入的长度 
     // totalBytesWritten -- 目前共写入的长度 
     // totalBytesExpectedToWrite -- 期望的长度,也就是总长度     
     // 在主线程中修改UI界面
      [[NSOperationQueue mainQueue]addOperationWithBlock:^{
      
      self.progressBar.progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;      
      self.precentLabel.text = [NSString stringWithFormat:@"%0.1f%%",self.progressBar.progress * 100];
          
      }];
      
      NSLog(@"%zd / %zd",totalBytesWritten,totalBytesExpectedToWrite);
  }
  
  // 完成下载的时候调用,系统默认将下载的文件存放到了沙盒的temp文件中
  - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  {
      // 剪切文件到Caches
      NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];      
      NSFileManager *mgr = [NSFileManager defaultManager]; 91     
      [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
      
      NSLog(@"didFinishDownloadingToURL");
  }
  // 任务完成的时候调用
  - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  {
      NSLog(@"didCompleteWithError"); 
 }  
 @end

简单的界面:

image
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • L二十九岁那年,还没生娃。 身边的人都在催:“赶紧生一个吧。” 听到这些话,她总是淡然一笑,从不把生孩子当成一种压...
    A曼均阅读 217评论 0 0
  • 书籍:《精力管理》 前一章作者对案例的生活危机进行了剖析,指出问题根源是对精力的过度损耗,才引发一系列恶果:超重,...
    5040MrYan阅读 593评论 0 1
  • 发表于2016年1月7日 对于求职的人来说,面试是不可缺少的一关,有的只是看一下长得是否漂亮,不过更多的是要面对面...
    如释笔记阅读 252评论 2 1
  • 那些没有消灭你的东西,会使你变得更强壮。 ——弗里德里希·威廉·尼采
    减焦糖阅读 239评论 0 0

友情链接更多精彩内容