一、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. TFIDF练习

    直接上代码吧: """ 测试Demo """ import lightgbm as lgb import numpy as np from ...

  2. acceptorThreadCount

    Apache Tomcat 7 Configuration Reference (7.0.92) - The HTTP Connector https://tomcat.apache.org/tomc ...

  3. 装饰器的修复wraps,偏函数partial 以及chain

    将被装饰的函数的一些属性值赋值给 装饰器函数,最终让属性的显示更符合我们的直觉. from functools import wraps def wapper(func): @wraps(func) ...

  4. mac常用操作:

    Mac常用软件需要熟悉 常用操作: command + w 关闭窗口  + n 最小化当前窗口  + m 关闭所有窗口  +  + w command + c 复制 command + v 粘贴 co ...

  5. constructor-arg和property的区别

    两者都是给bean注入属性,区别: constructor-arg:通过构造函数注入. property:通过setter对应的方法注入. 详情见:https://blog.csdn.net/u012 ...

  6. 20145204 《Java程序设计》第四周学习总结

    20145204 <Java程序设计>第四周学习总结 教材学习内容总结 继承 什么时候使用继承? 当多个类中出现重复定义的行为(即多个类中出现重复的代码)时,就把相同的程序代码提成为父类. ...

  7. FromBottomToTop第十一周项目博客

    FromBottomToTop第十一周项目博客 项目内容 塔防游戏 大体就是在地图上以合理阵型建设防御炮塔来阻止小怪进入我方阵地.玩家需用现有的金币进行炮台建设或升级,金币数可根据打怪个数增加.入侵的 ...

  8. asp.net web api的源码

    从安装的NuGet packages逆向找回去 <package id="Microsoft.AspNet.WebApi.Core" version="5.2.7& ...

  9. 斜率优化DP学习笔记

    先摆上学习的文章: orzzz:斜率优化dp学习 Accept:斜率优化DP 感谢dalao们的讲解,还是十分清晰的 斜率优化$DP$的本质是,通过转移的一些性质,避免枚举地得到最优转移 经典题:HD ...

  10. 【bzoj2721】[Violet 5]樱花

    题目传送门:https://www.lydsy.com/JudgeOnline/problem.php?id=2721 好久没做数学题了,感觉有些思想僵化,走火入魔了. 这道题就是求方程$ \frac ...