一、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. Oracle等待事件之Latch Free

    1.产生原因 表示某个锁存器上发生了竞争.首先应该确保已经提供了足够多的Latch 数,如果仍然发生这种等待事件,那么应该进一步确定是那种锁存器上发生了竞争(在v$session_wait 上的P2 ...

  2. Qunar机票技术部就有一个全年很关键的一个指标:搜索缓存命中率,当时已经做到了>99.7%。再往后,每提高0.1%,优化难度成指数级增长了。哪怕是千分之一,也直接影响用户体验,影响每天上万张机票的销售额。 在高并发场景下,提供了保证线程安全的对象、方法。比如经典的ConcurrentHashMap,它比起HashMap,有更小粒度的锁,并发读写性能更好。线程安全的StringBuilder取代S

    Qunar机票技术部就有一个全年很关键的一个指标:搜索缓存命中率,当时已经做到了>99.7%.再往后,每提高0.1%,优化难度成指数级增长了.哪怕是千分之一,也直接影响用户体验,影响每天上万张机 ...

  3. 不登录到MySQL执行SQL语句

    mysql -e 不登录到MySQL执行SQL语句 mysql -u root -p -e "SHOW DATABASES"

  4. mysql float 浮点型

    定点数类型 DEC等同于DECIMAL 浮点类型:FLOAT DOUBLE 作用:存储薪资.身高.体重.体质参数等 m,d 都是设置宽度 =============================== ...

  5. 204-React DOM 元素

    一.概述 为了提高性能和跨浏览器兼容性,React实现了一个独立于浏览器的DOM系统. 在React中,所有DOM属性和属性(包括事件处理程序)都应该是camelCased的.例如,HTML属性tab ...

  6. 表单(中)-EasyUI Combogrid 组合网格、EasyUI Numberbox 数字框、EasyUI Datebox 日期框、EasyUI Datetimebox 日期时间框、EasyUI Calendar 日历

    EasyUI Combogrid 组合网格 扩展自 $.fn.combo.defaults 和 $.fn.datagrid.defaults.通过 $.fn.combogrid.defaults 重写 ...

  7. VS2010/MFC编程入门之二十一(常用控件:编辑框Edit Control)

    鸡啄米上一节讲了静态文本框,本节要讲的编辑框(Edit Control)同样是一种很常用的控件,我们可以在编辑框中输入并编辑文本.在前面加法计算器的例子中已经演示了编辑框的基本应用.下面具体讲解编辑框 ...

  8. 32Sql数据库的插入

    上一节讲了数据库的连接,本例直接将数据库的插入操作,重点还是QSqlQuery类 QSqlQuery query; //新建二维表 query.exec("CREATE TABLE stud ...

  9. Qml应用程序的性能考虑与建议

    本文翻译自Qt官网文档: http://doc.qt.io/qt-5/qtquick-performance.html QtQml应用程序的性能考虑与建议 1.时间考虑 作为一名程序开发者,应该努力使 ...

  10. 聊一聊PV和并发、以及计算web服务器的数量的方法(转)

    转自:http://www.chinaz.com/web/2016/0817/567752.shtml 最近和几个朋友,聊到并发和服务器的压力问题.很多朋友,不知道该怎么去计算并发?部署多少台服务器才 ...