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

一、NSURLSession、NSURLSessionTask的使用步骤

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

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

  <2>NSURLSessionDownloadTask实现小文件的下载

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

  1 #import "ViewController.h"
  2 // 最好是用到哪个任务就实现哪种任务类型的代理协议
  3 @interface ViewController () <NSURLSessionDownloadDelegate>
  4 @property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
  5 @property (weak, nonatomic) IBOutlet UILabel *precentLabel;
  6 
  7 /** task */
  8 @property(nonatomic,strong) NSURLSessionDownloadTask *task;
  9 
 10 /** resumeData */
 11 @property(nonatomic,strong) NSData *resumeData;
 12 
 13 /** session */
 14 @property(nonatomic,strong) NSURLSession *session;
 15 
 16 @end
 17 
 18 @implementation ViewController
 19 
 20 - (NSURLSession *)session
 21 {
 22     if (_session == nil) {
 23         // 通过设置NSURLSession的Configuration来指定session的代理,以及代理的线程
 24         _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
 25     }
 26     return _session;
 27 }
 28 
 29 - (IBAction)start:(id)sender {
 30     
 31     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4"]];
 32     // 只通过request创建task  文件的具体下载通过代理来实现,
 33     self.task = [self.session downloadTaskWithRequest:request];
 34     
 35     [self.task resume];
 36     
 37 }
 38 - (IBAction)pause:(id)sender {
 39     // 取消任务 并产生一个恢复数据 -- 任务一旦取消就不能恢复
 40     [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
 41         // 将恢复数据存入变量
 42         self.resumeData = resumeData;
 43     }];
 44     
 45 }
 46 - (IBAction)goOn:(id)sender {
 47     
 48     // 任务已经被取消了,只能重新开启任务,通过resumeData继续下载任务
 49     self.task = [self.session downloadTaskWithResumeData:self.resumeData];
 50     
 51     // 恢复任务
 52     [self.task resume];
 53 }
 54 
 55 - (void)viewDidLoad {
 56     [super viewDidLoad];
 57     // Do any additional setup after loading the view, typically from a nib.
 58 }
 59 
 60 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
 61     
 62 }
 63 
 64 #pragma mark - <NSURLSessionDownloadDelegate>
 65 
 66 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
 67 {
 68     // bytesWritten -- 本次写入的长度
 69     // totalBytesWritten -- 目前共写入的长度
 70     // totalBytesExpectedToWrite -- 期望的长度,也就是总长度
 71     
 72     // 在主线程中修改UI界面
 73     [[NSOperationQueue mainQueue]addOperationWithBlock:^{
 74     
 75     self.progressBar.progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
 76     
 77     self.precentLabel.text = [NSString stringWithFormat:@"%0.1f%%",self.progressBar.progress * 100];
 78         
 79     }];
 80     
 81     NSLog(@"%zd / %zd",totalBytesWritten,totalBytesExpectedToWrite);
 82 }
 83 
 84 // 完成下载的时候调用,系统默认将下载的文件存放到了沙盒的temp文件中
 85 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
 86 {
 87     // 剪切文件到Caches
 88     NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
 89     
 90     NSFileManager *mgr = [NSFileManager defaultManager];
 91     
 92     [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
 93     
 94     NSLog(@"didFinishDownloadingToURL");
 95 }
 96 // 任务完成的时候调用
 97 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
 98 {
 99     NSLog(@"didCompleteWithError");
100 }
101 
102 @end
View Code

简单的界面:

原文地址:https://www.cnblogs.com/gchlcc/p/5449762.html