一、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
 

IOS-网络(NSURLSession)的更多相关文章

  1. iOS - 网络 - NSURLSession

    1.NSURLSession基础 NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃,现在最低版本一般适配iOS,所以也可以使用.NSURLCon ...

  2. iOS网络NSURLSession使用详解

    一.整体介绍 NSURLSession在2013年随着iOS7的发布一起面世,苹果对它的定位是作为NSURLConnection的替代者,然后逐步将NSURLConnection退出历史舞台.现在使用 ...

  3. iOS网络相关知识总结

    iOS网络相关知识总结 1.关于请求NSURLRequest? 我们经常讲的GET/POST/PUT等请求是指我们要向服务器发出的NSMutableURLRequest的类型; 我们可以设置Reque ...

  4. 【转载】一步一步搭建自己的iOS网络请求库

    一步一步搭建自己的iOS网络请求库(一) 大家好,我是LastDay,很久没有写博客了,这周会分享一个的HTTP请求库的编写经验. 简单的介绍 介绍一下,NSURLSession是iOS7中新的网络接 ...

  5. ios网络 -- HTTP请求 and 文件下载/断点下载

    一:请求 http://www.jianshu.com/p/8a90aa6bad6b 二:下载 iOS网络--『文件下载.断点下载』的实现(一):NSURLConnection http://www. ...

  6. iOS 网络监测

    iOS网络监测,监测单个页面写在ViewController里,监测全部写在AppDelegate中,而且不用终止 - (void)viewDidLoad { [super viewDidLoad]; ...

  7. iOS网络基础知识

    iOS网络基础知识 1.一次HTTP请求的完整过程 (1)浏览器或应用发起Http请求,请求包含Http请求Http(请求),地址(url),协议(Http1.1)请求为头部 (2)web服务器接收到 ...

  8. 【读书笔记】iOS网络-使用Bonjour实现自组织网络

    Bonjour就是这样一种技术:设备可以通过它轻松探测并连接到相同网络中的其他设备,整个过程只需要很少的用户参与或是根本就不需要用户参与.该框架提供了众多适合于移动的使用场景,如基于网络的游戏,设备间 ...

  9. 【读书笔记】iOS网络-使用Game Kit实现设备间通信

    Apple的Game Kit框架可以实现没有网络状况下的设备与设备之间的通信,这包括没有蜂窝服务,无法访问Wi-Fi基础设施以及无法访问局域网或Internet等情况.比如在丛林深处,高速公路上或是建 ...

  10. 【读书笔记】iOS网络-应用间通信

    一,URL方案 URL方案有3个主要用途:根据设备上其他应用的存在与否调整逻辑,切换到其他应用以及响应打开你的应用的其他应用.你还可以通过URL方案从某个站点或是在基于Web的认证流程结束是打开应用. ...

随机推荐

  1. Faster R-CNN论文详解 - CSDN博客

    废话不多说,上车吧,少年 paper链接:Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks ...

  2. Python开发【Django】:ModelForm操作

    ModelForm 内容回顾: Model - 数据库操作 - 验证 class A(MOdel): user = email = pwd = Form class LoginForm(Form): ...

  3. 理解Java异常处理机制的机理

    重看异常机制的时候觉得抓到了点机理上的精髓,所以来说一下,对初学者应该会有些帮助   JAVA中的异常机制 从机制上由[产生异常][抛出异常][捕捉异常][异常处理]组成 从形式上又分为四种: 运行时 ...

  4. 9.GIt删除操作

    在Git中,删除也是一个修改操作,我们实战一下,先添加一个新文件test.txt到Git并且提交: 创建一个文件test.txt,写入一句话`this is new file !`. $ echo ' ...

  5. mysql 整数类型 数值类型 tinyint

    1.整数类型 整数类型:TINYINT SMALLINT MEDIUMINT INT BIGINT 作用:存储年龄,等级,id,各种号码等 ============================== ...

  6. 001-ant design安装及快速入门【基于纯antd的基本项目搭建】

    一.安装使用 1.1.安装 推荐使用 npm 或 yarn 的方式进行开发 npm install antd --save yarn add antd 1.2.浏览器引入 在浏览器中使用 script ...

  7. 007-spring cache-缓存实现-02-springboot ehcahe3实现、springboot caffeine实现

    一.springboot ehcahe3实现步骤 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认CacheProvider.Ehcache是一种广泛 ...

  8. Java-idea-FindBugs、PMD和CheckStyle对比

    一.对比 工具 目的 检查项 备注 FindBugs 检查.class 基于Bug Patterns概念,查找javabytecode (.class文件)中的潜在bug 主要检查bytecode中的 ...

  9. (转)在GitHub多个帐号上添加SSH公钥

    GitHub后台可以添加多个SSH Keys,但是同一个SSH Keys只能在添加在一个帐号上(添加时提示“Key is already in use”).理由很容易想到,SSH公钥使用时相当于用户名 ...

  10. 自定义 Repository 方法

    为某一个 Repository 上添加自定义方法 步骤: 定义一个接口: 声明要添加的, 并自实现的方法 提供该接口的实现类: 类名需在要声明的 Repository 后添加 Impl, 并实现方法 ...