一、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. talib 中文文档(九):# Volatility Indicator Functions 波动率指标函数

    Volatility Indicator Functions 波动率指标函数 ATR - Average True Range 函数名:ATR 名称:真实波动幅度均值 简介:真实波动幅度均值(ATR) ...

  2. mysql备份的4种方式

    mysql备份的4种方式 转载自:https://www.cnblogs.com/SQL888/p/5751631.html 总结: 备份方法 备份速度 恢复速度 便捷性 功能 一般用于 cp 快 快 ...

  3. 《玩转Spring》第二章 BeanPostProcessor扩展

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/shan9liang/article/details/34421141 上一章.介绍了怎样扩展spri ...

  4. centos 正则,grep,egrep,流式编辑器 sed,awk -F 多个分隔符 通配符 特殊符号. * + ? 总结 问加星 cat -n nl 输出文件内容并加上行号 alias放~/.bash_profile 2015-4-10 第十三节课

    centos 正则,grep,egrep,流式编辑器 sed,awk -F 多个分隔符  通配符 特殊符号. * + ? 总结  问加星 cat -n  nl  输出文件内容并加上行号 alias放~ ...

  5. 优雅的使用Laravel之phpstorm配置

    优雅的使用Laravel之phpstorm配置 先打开一个Laravel 项目,然后在project tool 窗口选择根节点.然后右键->Composer | Init composer . ...

  6. [py][lc]python的纸牌知识点

    模块collections-collections.namedtuple表示tuple 如表示一个坐标, t = (1,2), 搞不清楚. 如果这样就对了Point(x=1, y=2) from co ...

  7. js中var a={}什么意思

    创建一个变量a, 并给a赋值:{}是一个空的对象,是 new Object();的简写.

  8. CCPC-Wannafly Winter Camp Day2 (Div2, onsite)

    Class $A_i = a \cdot i \% n$ 有 $A_i = k \cdot gcd(a, n)$ 证明: $A_0 = 0, A_x = x \cdot a - y \cdot n$ ...

  9. poj1329 Circle Through Three Points

    地址:http://poj.org/problem?id=1329 题目: Circle Through Three Points Time Limit: 1000MS   Memory Limit: ...

  10. zw版【转发·台湾nvp系列Delphi例程】HALCON SqrtImage

    zw版[转发·台湾nvp系列Delphi例程]HALCON SqrtImageHALCON SqrtImage 範例 (RAD Studio XE Delphi x64) zw版[转发·台湾nvp系列 ...