IOS-网络(NSURLSession)
2016-02-02 00:18
525 查看
一、NSURLSession的基本用法
二、NSURLSession的断点续传
// // ViewController.m // NSURLSession // // Created by ma c on 16/2/1. // Copyright © 2016年 博文科技. All rights reserved. // #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> @end @implementation ViewController /* 任务:任何请求都是一个任务 NSURLSessionDataTask:普通的GET、POST请求 NSURLSessionDownloadTask:文件下载 NSURLSessionUploadTask:文件上传 注意:如果给下载任务设置了completionHandler这个block,也实现了下载代理方法,优先执行block */ - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor cyanColor]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // [self sendGetRequest]; // [self sendPostRequest]; // [self downlaodTask1]; [self downlaodTask2]; } #pragma mark - NSURLSessionDownloadTask2 ///下载任务(有下载进度) - (void)downlaodTask2 { //1.创建Session对象 NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //2.创建一个任务 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"]; NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url]; //3.开始任务 [task resume]; } #pragma mark - NSURLSessionDownloadDelegate的代理方法 ///下载完毕时调用 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSLog(@"didFinishDownloadingToURL--->%@",location); //location:文件的临时路径,下载好的文件 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, nil) lastObject]; NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; //降临时文件夹,剪切或者复制到Caches文件夹 NSFileManager *mgr = [NSFileManager defaultManager]; [mgr moveItemAtPath:location.path toPath:file error:nil]; } ///恢复下载时调用 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { } ///每当写完一部分就调用(根据文件大小调用多次) //bytesWritten: 这次调用写了多少 //totalBytesWritten: 累计写了多少长度到沙河中 //totalBytesExpectedToWrite:文件的总长度 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { double progress = (double)totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"下载进度--->%lf",progress); } #pragma mark - NSURLSessionDownloadTask1 ///下载任务(不能看到下载进度) - (void)downlaodTask1 { //1.创建Session对象 NSURLSession *session = [NSURLSession sharedSession]; //2.创建NSURL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"]; NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { //location:文件的临时路径,下载好的文件 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, nil) lastObject]; NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename]; //降临时文件夹,剪切或者复制到Caches文件夹 NSFileManager *mgr = [NSFileManager defaultManager]; [mgr moveItemAtPath:location.path toPath:file error:nil]; //[mgr copyItemAtPath:location.path toPath:file error:nil]; }]; //3.开始任务 [task resume]; } #pragma mark - NSURLSessionDataTask ///POST请求 - (void)sendPostRequest { //1.创建Session对象 NSURLSession *session = [NSURLSession sharedSession]; //2.创建NSURL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login"]; //3.创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; //4.设置请求体 request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding]; //5.创建一个任务 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"sendPostRequest:%@",dict); }]; //6.开始任务 [task resume]; } ///GET请求 - (void)sendGetRequest { //1.得到session对象 NSURLSession *session = [NSURLSession sharedSession]; //2.创建一个任务 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"]; NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"sendGetRequest:%@",dict); }]; //3.开始任务 [task resume]; } @end
二、NSURLSession的断点续传
// // ViewController.m // IOS_0204_NSURLSession断点续传 // // Created by ma c on 16/2/4. // Copyright © 2016年 博文科技. All rights reserved. // #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> - (IBAction)btnClick:(UIButton *)sender; @property (weak, nonatomic) IBOutlet UIButton *btnClick; @property (weak, nonatomic) IBOutlet UIProgressView *progressView; @property (nonatomic, strong) NSURLSessionDownloadTask *task; @property (nonatomic, strong) NSData *resumeData; @property (nonatomic, strong) NSURLSession *session; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.progressView.progress = 0.01; } - (NSURLSession *)session { if (!_session) { //获得session NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration]; _session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]]; } return _session; } - (IBAction)btnClick:(UIButton *)sender { //取反 sender.selected = !sender.isSelected; if (sender.selected) { //开始、恢复下载 if (self.resumeData) { //恢复下载 [self resume]; } else { //开始下砸 [self start]; } } else { //暂停下载 [self pause]; } } //从零开始下载 - (void)start { //1.创建一个下载任务 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_01.mp4"]; self.task = [self.session downloadTaskWithURL:url]; //2.开始任务 [self.task resume]; } //继续下载 - (void)resume { //传入上次暂停下载返回的数据,就可以恢复下载 self.task = [self.session downloadTaskWithResumeData:self.resumeData]; [self.task resume]; } //暂停下载 - (void)pause { __weak typeof(self) vc = self; [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) { //resumeData:包含了下载的开始位置 vc.resumeData = resumeData; vc.task = nil; }]; } #pragma mark - NSURLSessionDownloadDelegate的代理方法 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { self.btnClick.selected = !self.btnClick.isSelected; NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; //suggestedFilename建议使用的文件名,一般与服务器端的文件名一致 NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; //NSLog(@"%@",file); NSFileManager *mgr = [NSFileManager defaultManager]; //将临时文件复制或者剪切到caches文件夹 [mgr moveItemAtPath:location.path toPath:file error:nil]; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { } - (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; } @end
相关文章推荐
- Android OkHttp完全解析 是时候来了解OkHttp了
- HTTP状态码
- 基于libsmart的网络编程示例之EchoServer
- nginx使用ssl模块配置HTTPS支持
- http的方式访问HDFS
- 在 JS 中使用 fetch 更加高效地进行网络请求
- HTTP协议—— 简单认识TCP/IP协议
- HttpClient使用笔记
- HTTP2.0那些事
- 网络OSI参考模型
- Broadleaf电商系统开发(五) - Http Api
- 全面解析4G LTE网络三大主流语音解决方案
- 在iOS9 中,苹果将原http协议改成了https协议,使用 TLS1.2 SSL加密请求数据。要使用HTTP要修改PTLIST
- 用Fiddler在Android上抓HTTPS包
- android 6.0(api 23) SDK,不再提供org.apache.http.*(只保留几个类)
- OTN交换&P-OTN有效减少100G网络成本(一)
- ssh使用http代理登录工具
- TCP三次握手四次挥手过程详解
- 图文介绍HTTP/2(特性、解决的问题、实现方法)
- HttpClient超时设置_demo