zoukankan      html  css  js  c++  java
  • IOS-网络(NSURLSession)

     一、NSURLSession的基本用法

      1 //
      2 //  ViewController.m
      3 //  NSURLSession
      4 //
      5 //  Created by ma c on 16/2/1.
      6 //  Copyright © 2016年 博文科技. All rights reserved.
      7 //
      8 
      9 #import "ViewController.h"
     10 
     11 @interface ViewController ()<NSURLSessionDownloadDelegate>
     12 
     13 @end
     14 
     15 @implementation ViewController
     16 /*
     17  任务:任何请求都是一个任务
     18  
     19  NSURLSessionDataTask:普通的GET、POST请求
     20  NSURLSessionDownloadTask:文件下载
     21  NSURLSessionUploadTask:文件上传
     22  
     23  注意:如果给下载任务设置了completionHandler这个block,也实现了下载代理方法,优先执行block
     24 
     25  */
     26 - (void)viewDidLoad {
     27     [super viewDidLoad];
     28     
     29     self.view.backgroundColor = [UIColor cyanColor];
     30 
     31 }
     32 
     33 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
     34 {
     35 //    [self sendGetRequest];
     36 //    [self sendPostRequest];
     37 //    [self downlaodTask1];
     38     [self downlaodTask2];
     39 }
     40 
     41 #pragma mark - NSURLSessionDownloadTask2
     42 ///下载任务(有下载进度)
     43 - (void)downlaodTask2
     44 {
     45     //1.创建Session对象
     46     NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
     47     NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
     48     //2.创建一个任务
     49     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"];
     50     NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
     51     //3.开始任务
     52     [task resume];
     53 }
     54 
     55 #pragma mark - NSURLSessionDownloadDelegate的代理方法
     56 ///下载完毕时调用
     57 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
     58 {
     59     NSLog(@"didFinishDownloadingToURL--->%@",location);
     60     //location:文件的临时路径,下载好的文件
     61     NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, nil) lastObject];
     62     NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
     63     
     64     //降临时文件夹,剪切或者复制到Caches文件夹
     65     NSFileManager *mgr = [NSFileManager defaultManager];
     66     [mgr moveItemAtPath:location.path toPath:file error:nil];
     67 }
     68 ///恢复下载时调用
     69 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
     70 {
     71     
     72 }
     73 ///每当写完一部分就调用(根据文件大小调用多次)
     74 //bytesWritten:             这次调用写了多少
     75 //totalBytesWritten:        累计写了多少长度到沙河中
     76 //totalBytesExpectedToWrite:文件的总长度
     77 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
     78 {
     79     double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
     80     
     81     NSLog(@"下载进度--->%lf",progress);
     82     
     83 }
     84 
     85 #pragma mark - NSURLSessionDownloadTask1
     86 ///下载任务(不能看到下载进度)
     87 - (void)downlaodTask1
     88 {
     89     //1.创建Session对象
     90     NSURLSession *session = [NSURLSession sharedSession];
     91     //2.创建NSURL
     92     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"];
     93     NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
     94        //location:文件的临时路径,下载好的文件
     95         NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, nil) lastObject];
     96         NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
     97         
     98         //降临时文件夹,剪切或者复制到Caches文件夹
     99         NSFileManager *mgr = [NSFileManager defaultManager];
    100         [mgr moveItemAtPath:location.path toPath:file error:nil];
    101         
    102         //[mgr copyItemAtPath:location.path toPath:file error:nil];
    103         
    104         
    105     }];
    106     //3.开始任务
    107     [task resume];
    108 }
    109 
    110 
    111 #pragma mark - NSURLSessionDataTask
    112 ///POST请求
    113 - (void)sendPostRequest
    114 {
    115     //1.创建Session对象
    116     NSURLSession *session = [NSURLSession sharedSession];
    117     
    118     //2.创建NSURL
    119     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login"];
    120     //3.创建请求
    121     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    122     request.HTTPMethod = @"POST";
    123     //4.设置请求体
    124     request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
    125     //5.创建一个任务
    126     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    127         
    128         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
    129                                                              options:NSJSONReadingMutableLeaves error:nil];
    130         NSLog(@"sendPostRequest:%@",dict);
    131     }];
    132     //6.开始任务
    133     [task resume];
    134 }
    135 
    136 ///GET请求
    137 - (void)sendGetRequest
    138 {
    139     //1.得到session对象
    140     NSURLSession *session = [NSURLSession sharedSession];
    141     //2.创建一个任务
    142     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];
    143     NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    144         
    145         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
    146                                                              options:NSJSONReadingMutableLeaves error:nil];
    147         NSLog(@"sendGetRequest:%@",dict);
    148     }];
    149     //3.开始任务
    150     [task resume];
    151 }
    152 @end

     二、NSURLSession的断点续传

      1 //
      2 //  ViewController.m
      3 //  IOS_0204_NSURLSession断点续传
      4 //
      5 //  Created by ma c on 16/2/4.
      6 //  Copyright © 2016年 博文科技. All rights reserved.
      7 //
      8 
      9 #import "ViewController.h"
     10 
     11 @interface ViewController ()<NSURLSessionDownloadDelegate>
     12 
     13 - (IBAction)btnClick:(UIButton *)sender;
     14 @property (weak, nonatomic) IBOutlet UIButton *btnClick;
     15 @property (weak, nonatomic) IBOutlet UIProgressView *progressView;
     16 
     17 @property (nonatomic, strong) NSURLSessionDownloadTask *task;
     18 @property (nonatomic, strong) NSData *resumeData;
     19 @property (nonatomic, strong) NSURLSession *session;
     20 
     21 @end
     22 
     23 @implementation ViewController
     24 
     25 - (void)viewDidLoad {
     26     [super viewDidLoad];
     27     
     28     self.progressView.progress = 0.01;
     29 }
     30 
     31 - (NSURLSession *)session
     32 {
     33     if (!_session) {
     34         //获得session
     35         NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
     36         _session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
     37     }
     38     return _session;
     39 }
     40 
     41 
     42 - (IBAction)btnClick:(UIButton *)sender {
     43     //取反
     44     sender.selected = !sender.isSelected;
     45     
     46     if (sender.selected) { //开始、恢复下载
     47         
     48         if (self.resumeData) { //恢复下载
     49             [self resume];
     50             
     51         } else {  //开始下砸
     52             [self start];
     53         }
     54         
     55     } else { //暂停下载
     56         [self pause];
     57     }
     58 }
     59 //从零开始下载
     60 - (void)start
     61 {
     62     //1.创建一个下载任务
     63     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_01.mp4"];
     64     self.task = [self.session downloadTaskWithURL:url];
     65     //2.开始任务
     66     [self.task resume];
     67 }
     68 //继续下载
     69 - (void)resume
     70 {
     71     //传入上次暂停下载返回的数据,就可以恢复下载
     72     self.task = [self.session downloadTaskWithResumeData:self.resumeData];
     73     
     74     [self.task resume];
     75 }
     76 //暂停下载
     77 - (void)pause
     78 {
     79     __weak typeof(self) vc = self;
     80     [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
     81         
     82         //resumeData:包含了下载的开始位置
     83         vc.resumeData = resumeData;
     84         vc.task = nil;
     85         
     86     }];
     87 }
     88 #pragma mark - NSURLSessionDownloadDelegate的代理方法
     89 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
     90 {
     91     self.btnClick.selected = !self.btnClick.isSelected;
     92     
     93     NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
     94     //suggestedFilename建议使用的文件名,一般与服务器端的文件名一致
     95     NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
     96     //NSLog(@"%@",file);
     97     NSFileManager *mgr = [NSFileManager defaultManager];
     98     //将临时文件复制或者剪切到caches文件夹
     99     [mgr moveItemAtPath:location.path toPath:file error:nil];
    100     
    101 }
    102 
    103 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
    104 {
    105     
    106 }
    107 
    108 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
    109 {
    110     //获得下载进度
    111     self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
    112 }
    113 @end
     
  • 相关阅读:
    ASP.NET——基础 14、Server
    ASP.NET——基础 15、HttpHandler
    ASP.NET——基础 2、ViewState
    MYSQL VS2010 中文乱码问题
    ASP.NET——基础 10、Web开发的一些基本原则1
    数据结构与算法 2、单向/双向链表
    C#操作XML日志
    web开发入门级学习经验(菜鸟级)
    笔记:键盘键值一览表(JS)
    笔记:JS事件的捕获与冒泡
  • 原文地址:https://www.cnblogs.com/oc-bowen/p/5176607.html
Copyright © 2011-2022 走看看