zoukankan      html  css  js  c++  java
  • NSURLSession详解

    导语

    • 现在NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃,现在最低版本一般适配iOS7,所以也可以使用。

    • NSURLConnection相对于NSURLSession,安全性低。NSURLConnection下载有峰值,比较麻烦处理。
    • 尽管适配最低版本iOS7,也可以使用NSURLSession。AFN已经不支持NSURLConnection。
    •  NSURLSession:默认是挂起状态,如果要请求网络,需要开启。

         [NSURLSession sharedSession] 获取全局的NSURLSession对象。在iPhone的所有app共用一个全局session.
         NSURLSessionUploadTask -> NSURLSessionDataTask -> NSURLSessionTask
         NSURLSessionDownloadTask -> NSURLSessionTask
         NSURLSessionDownloadTask下载,默认下载到tmp文件夹。下载完成后删除临时文件。所以我们要在删除文件之前,将它移动到Cache里。

    NSURLSession详解

    1. NSURLSession基础

    2. NSURLSession代理
    3. NSURLSession大文件下载
    4. NSURLSession断点续传

    1.NSURLSession基础

    • 第一种网络请求方法  
        //创建URL
        NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
        //创建请求
        //    NSURLRequest * request = [NSURLRequest requestWithURL:url];
        //创建Session
        NSURLSession * session = [NSURLSession sharedSession];
        //创建任务
        NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }];
        //开启网络任务
        [task resume];
    • 第二种网络请求方法
    //创建URL
        NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
        //创建请求
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        //创建Session
        NSURLSession * session = [NSURLSession sharedSession];
        //创建任务
        NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            
        }];
        //开启网络任务
        [task resume];
    • POST请求
    NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php"];
        
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
        
        //设置请求方法
        request.HTTPMethod = @"POST";
        
        //设置请求体
        request.HTTPBody = [@"username=haha&password=123" dataUsingEncoding:NSUTF8StringEncoding];
        
        [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            
        }] resume];
    • 下载文件
        NSURL * url = [NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        NSURLSession * session = [NSURLSession sharedSession];
    
        NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            //location 下载到沙盒的地址
            NSLog(@"下载完成%@",location);
        
            //response.suggestedFilename 响应信息中的资源文件名
            NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
            
            NSLog(@"缓存地址%@",cachesPath);
            
            //获取文件管理器
            NSFileManager * mgr = [NSFileManager defaultManager];
            //将临时文件移动到缓存目录下
            //[NSURL fileURLWithPath:cachesPath] 将本地路径转化为URL类型
            //URL如果地址不正确,生成的url对象为空
            
            [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];
            
        }];
        
        [downloadTask resume];

    2.NSURLSession代理

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
     
        
        //  全局session
        //    NSURLSession * session = [NSURLSession sharedSession];
        //创建自定义session
        //NSURLSessionConfiguration 的 配置
        //[[NSOperationQueue alloc] init] 也可以写成 nil
    
        NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
        
        NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
        
        NSURLSessionDataTask * task = [session dataTaskWithURL:url];
        
        [task resume];
        
    }
    
    //接收到服务器响应
    
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveResponse:(NSURLResponse *)response
     completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
        
        NSLog(@"%s",__FUNCTION__);
        
        //允许接受服务器回传数据
        completionHandler(NSURLSessionResponseAllow);
    }
    
    //接收服务器回传的数据,有可能执行多次
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
        didReceiveData:(NSData *)data {
        
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }
    
    //请求成功或失败
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
        
        NSLog(@"%@",error);
    }

    3.NSURLSession大文件下载

    #import "ViewController.h"
    
    @interface ViewController ()<NSURLSessionDownloadDelegate>
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1));
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        
        NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
        
        NSURLSessionDownloadTask * task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        
        [task resume];
    
    }
    
    /* 
     
     监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次
     
     bytesWritten 单次写入多少
     totalBytesWritten  已经写入了多少
     totalBytesExpectedToWrite 文件总大小
     
     */
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
          didWriteData:(int64_t)bytesWritten
     totalBytesWritten:(int64_t)totalBytesWritten
    totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
        
        //打印下载百分比
        NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
        
    }
    
    //下载完成
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
    didFinishDownloadingToURL:(NSURL *)location {
        
        
        NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
        
        NSFileManager * mgr = [NSFileManager defaultManager];
        
        [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];
        
    }
    
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
        
        NSLog(@"%@",error);
    }

    4.NSURLSession断点续传

    #import "ViewController.h"
    
    @interface ViewController ()<NSURLSessionDownloadDelegate>
    
    @property (nonatomic, strong) NSURLSessionDownloadTask * task;
    
    @property (nonatomic, strong) NSData * resumeData;
    
    @property (nonatomic, strong) NSURLSession * session;
    
    @end
    
    @implementation ViewController
    
    //故事板中开始按钮的响应方法
    - (IBAction)start:(id)sender {
        
        NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
        
        self.session = session;
    
        self.task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.68/丁香花.mp3"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        
        [self.task resume];
    }
    
    //故事板中暂停按钮的响应方法
    - (IBAction)pause:(id)sender {
        
        //暂停就是将任务挂起
        
        [self.task cancelByProducingResumeData:^(NSData *resumeData) {
            //保存已下载的数据
    
            self.resumeData = resumeData;
        }];
    }
    //继续按钮的响应方法
    - (IBAction)resume:(id)sender {
        
        //可以使用ResumeData创建任务
        
        self.task = [self.session downloadTaskWithResumeData:self.resumeData];
        
        //开启继续下载
        [self.task resume];
        
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1));
    }
    
    
    /* 
     
     监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次
     
     bytesWritten 单次写入多少
     totalBytesWritten  已经写入了多少
     totalBytesExpectedToWrite 文件总大小
     
     */
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
          didWriteData:(int64_t)bytesWritten
     totalBytesWritten:(int64_t)totalBytesWritten
    totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
        
        //打印下载百分比
        NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
        
    }
    
    //下载完成
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
    didFinishDownloadingToURL:(NSURL *)location {
        
        
        NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
        
        NSFileManager * mgr = [NSFileManager defaultManager];
        
        [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];
        
    }
    
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
        
        NSLog(@"%@",error);
    }
  • 相关阅读:
    leetcode 1301. 最大得分的路径数目
    LeetCode 1306 跳跃游戏 III Jump Game III
    LeetCode 1302. 层数最深叶子节点的和 Deepest Leaves Sum
    LeetCode 1300. 转变数组后最接近目标值的数组和 Sum of Mutated Array Closest to Target
    LeetCode 1299. 将每个元素替换为右侧最大元素 Replace Elements with Greatest Element on Right Side
    acwing 239. 奇偶游戏 并查集
    acwing 238. 银河英雄传说 并查集
    acwing 237程序自动分析 并查集
    算法问题实战策略 MATCHORDER 贪心
    Linux 安装Redis全过程日志
  • 原文地址:https://www.cnblogs.com/ldnh/p/5304279.html
Copyright © 2011-2022 走看看