zoukankan      html  css  js  c++  java
  • NSURLSession 简介

    步骤:
    (1) 得到 session 对象, NSURLSession *session = [NSURLSession sharedSession];
    (2) 创建一个task, 任何一个请求都是一个任务

    NSURLSessionDataTask // 普通任务
    NSURLSessionDownLoadTask // 文件下载任务
    NSURLSessionUploadTask // 文件上传任务

    NSURLSession 实现 GET 请求

    - (IBAction)login {
        //判断账号与密码是否为空
        NSString *name = _accountText.text;
        if (name == nil || name.length == 0){
            NSLog(@"请输入账号");
            return;
        }
    
        NSString *pwd = _pwdText.text;
        if (pwd == nil || pwd.length == 0){
            NSLog(@"请输入密码");
            return;
        }
    
        //创建URL
        NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/Server/login?username=%@&pwd=%@", name, pwd];
    
        //用NSURLSession实现登录
        [self sessionWithUrl:urlStr];
    }
    
    - (void)sessionWithUrl:(NSString *)urlStr{
        NSURL *url = [NSURL URLWithString:urlStr];
    
        //用NSURLConnection实现登录
         NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"GET";
    
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data == nil || error != nil) {
                NSLog(@"请求失败");
                return;
            }
    
            //JSON解析
            NSError *error2;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error2];
            if (error2) {
                NSLog(@"解析失败 -- %@", error2);
            }
            NSLog(@"数据为 -- %@", dict);
        }];
        [task resume];
    
    }

    NSURLSession 实现 POST 请求:

    - (IBAction)login {
        //判断账号与密码是否为空
        NSString *name = _accountText.text;
        if (name == nil || name.length == 0){
            NSLog(@"请输入账号");
            return;
        }
    
        NSString *pwd = _pwdText.text;
        if (pwd == nil || pwd.length == 0){
            NSLog(@"请输入密码");
            return;
        }
    
    
        //用NSURLSession实现登录
        //创建URL
        NSString *urlStr = @"http://localhost:8080/Server/login";
        [self sessionWithUrl:urlStr];
    }
    
    - (void)sessionWithUrl:(NSString *)urlStr{
        NSURL *url = [NSURL URLWithString:urlStr];
    
        //用NSURLConnection实现登录
         NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        //POST请求
        request.HTTPMethod = @"POST";
        NSString *prama = [NSString stringWithFormat:@"username=%@&pwd=%@", _accountText.text, _pwdText.text];
        //中文转码
        [prama stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //转码
        request.HTTPBody = [prama dataUsingEncoding:NSUTF8StringEncoding];
    
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data == nil || error != nil) {
                NSLog(@"请求失败");
                return;
            }
    
            //JSON解析
            NSError *error2;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error2];
            if (error2) {
                NSLog(@"解析失败 -- %@", error2);
            }
            NSLog(@"数据为 -- %@", dict);
        }];
        [task resume];
    
    }
    

    NSURLSession 实现 断点续传:

    //断点下载
    @property (nonatomic, strong) NSURLSession *session;
    @property (nonatomic, strong) NSURLSessionDownloadTask *task;
    @property (nonatomic, strong) NSData *resumeData;
    @property (weak, nonatomic) IBOutlet UIProgressView *progressView;
    
    //懒加载
    - (NSURLSession *)session{
        if (!_session) {
            NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
            _session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        }
        return _session;
    }
    
    /**
     *  NSURLSession实现断点下载
     */
    - (IBAction)startDowbLoad:(id)sender {
        NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos/minion_01.mp4"];
        self.task = [self.session downloadTaskWithURL:url];
        //开始下载
        [self.task resume];
    }
    
    /**
     *  暂停下载
     */
    - (IBAction)pauseDownLoad:(id)sender{
        __weak typeof (self) vc = self;
        /**
         *  @param resumeData 包含了继续下载开始的位置和下载的URL
         */
        [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            vc.resumeData = resumeData;
            self.task = nil;
        }];
    }
    
    /**
     *  恢复下载
     */
    - (IBAction)resumeDownLoad:(id)sender {
        //传入上次下载的数据
        self.task = [self.session downloadTaskWithResumeData:self.resumeData];
        //开始下载
        [self.task resume];
        //清空
        self.resumeData = nil;
    }
    
    #pragma mark - NSURLSessionDelegate 代理方法
    //下载完成调用
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
        //下载完成后,写入 caches 文件中
        NSString *cachesFile = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
        NSFileManager *mgr = [NSFileManager defaultManager];
        [mgr moveItemAtPath:location.path toPath:cachesFile error:nil];
    }
    
    /**
     *  下载过程中调用这个方法, 每当下载完(写完)一部分时会调用, (可能被调用多次)
     *
     *  @param bytesWritten              这次写了多少
     *  @param totalBytesWritten         累计写了多少
     *  @param totalBytesExpectedToWrite 文件的总长度
     */
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
        self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
    }
    
    //恢复下载的时候调用
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    
    }
  • 相关阅读:
    [Python3网络爬虫开发实战] 1.2.6-aiohttp的安装
    [Python3网络爬虫开发实战] 1.3.1-lxml的安装
    [Python3网络爬虫开发实战] 1.2.5-PhantomJS的安装
    [Python3网络爬虫开发实战] 1.2.3-ChromeDriver的安装
    [Python3网络爬虫开发实战] 1.2.4-GeckoDriver的安装
    [Python3网络爬虫开发实战] 1.2.2-Selenium的安装
    [Python3网络爬虫开发实战] 1.2.1-Requests的安装
    tensorflow 根据节点名称获取节点
    tensorflow 根据节点获取节点前的整张图
    tf.estimator.Estimator
  • 原文地址:https://www.cnblogs.com/xiaocai-ios/p/7779769.html
Copyright © 2011-2022 走看看