zoukankan      html  css  js  c++  java
  • 网络热恋之NSURLSession

    //
    //  ViewController.m
    //  NSURLSession代理简介
    
    #import "ViewController.h"
    
    @interface ViewController ()<NSURLSessionDataDelegate>
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
    }
    //这是为了测试而建立的点击屏幕事件。
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
        
        //代理 测试
        
        NSURL * url = [NSURL URLWithString:@"http://localhost/login.php?username=haha&password=123"];
    
        //创建自定义Session
        
        NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
        
        NSURLSessionTask * task = [session dataTaskWithURL:url];
        //开启任务
        [task resume];
        
    }
    #pragma mark - deleDate
    //接受到服务器响应
    -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
    {
        //__FUNCTION__ c语言字符串用s
        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 didBecomeInvalidWithError:(NSError *)error{
        NSLog(@"%@",error);
    }
    @end

    上面简单介绍了一下

    然后我们来看一个demo

    其中下载文件的地址,读者可以自己配置

      1 //
      2 //  ViewController.m
      3 //  NSURLSession大文件下载
      4 //
      5 //
      6 
      7 #import "ViewController.h"
      8 
      9 @interface ViewController ()<NSURLSessionDownloadDelegate>
     10 
     11 @property (nonatomic, strong) NSURLSessionDownloadTask * task;
     12 
     13 @property (nonatomic, strong) NSData * resumeData;
     14 
     15 @property (nonatomic, strong) NSURLSession * session;
     16 
     17 @end
     18 
     19 @implementation ViewController
     20 
     21 
     22 - (IBAction)start:(id)sender {
     23     
     24     NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
     25     
     26     self.session = session;
     27 
     28     self.task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
     29     
     30     [self.task resume];
     31 }
     32 
     33 
     34 - (IBAction)pause:(id)sender {
     35     
     36     //暂停就是将任务挂起
     37     
     38     [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
     39         
     40         //保存已下载的数据
     41         self.resumeData = resumeData;
     42     }];
     43 }
     44 
     45 - (IBAction)resume:(id)sender {
     46     
     47     //可以使用ResumeData创建任务
     48     
     49     self.task = [self.session downloadTaskWithResumeData:self.resumeData];
     50     
     51     //开启继续下载
     52     [self.task resume];
     53     
     54 }
     55 
     56 - (void)viewDidLoad {
     57     [super viewDidLoad];
     58     // Do any additional setup after loading the view, typically from a nib.
     59     
     60     NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1));
     61 }
     62 
     63 
     64 /* 
     65  
     66  监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次
     67  
     68  bytesWritten 单次写入多少
     69  totalBytesWritten  已经写入了多少
     70  totalBytesExpectedToWrite 文件总大小
     71  
     72  */
     73 
     74 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
     75       didWriteData:(int64_t)bytesWritten
     76  totalBytesWritten:(int64_t)totalBytesWritten
     77 totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
     78     
     79     //打印下载百分比
     80     NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
     81     
     82 }
     83 
     84 //下载完成
     85 
     86 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
     87 didFinishDownloadingToURL:(NSURL *)location {
     88     
     89     
     90     NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
     91     
     92     NSFileManager * mgr = [NSFileManager defaultManager];
     93     
     94     [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];
     95     
     96 }
     97 
     98 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
     99     
    100     NSLog(@"%@",error);
    101 }
    102 
    103 - (void)didReceiveMemoryWarning {
    104     [super didReceiveMemoryWarning];
    105     // Dispose of any resources that can be recreated.
    106 }
    107 
    108 @end
  • 相关阅读:
    使用python内置模块os和openpyxl搜索指定文件夹下Excel中的内容
    python实现DNA序列字符串转换,互补链,反向链,反向互补链
    PandaSeq安装报错ltld required, install libtool library
    使用MySQL客户端登录Ensemble数据库查询相关信息
    第118天:移动端开发——视口
    第117天:Ajax实现省市区三级联动
    第116天: Ajax运用artTemplate实现菜谱
    第115天:Ajax 中artTemplate模板引擎(一)
    第114天:Ajax跨域请求解决方法(二)
    第113天:Ajax跨域请求解决方法
  • 原文地址:https://www.cnblogs.com/iOSlearner/p/5381406.html
Copyright © 2011-2022 走看看