导语

  • 现在NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃,现在最低版本一般适配iOS7,所以也可以使用。

  • NSURLConnection相对于NSURLSession,安全性低。NSURLConnection下载有峰值,比较麻烦处理。
  • 尽管适配最低版本iOS7,也可以使用NSURLSession。AFN已经不支持NSURLConnection。
  • NSURLSession:默认是挂起状态,如果要请求网络,需要开启。

[NSURLSession sharedSession] 获取全局的NSURLSession对象。在iPhone的所有app共用一个全局session.
     NSURLSessionUploadTask -> NSURLSessionDataTask -> NSURLSessionTask
     NSURLSessionDownloadTask -> NSURLSessionTask
     NSURLSessionDownloadTask下载,默认下载到tmp文件夹。下载完成后删除临时文件。所以我们要在删除文件之前,将它移动到Cache里。

NSURLSession详解

  1. NSURLSession基础

  2. NSURLSession代理
  3. NSURLSession大文件下载
  4. NSURLSession断点续传

1.NSURLSession基础

  • 第一种网络请求方法
    //创建URL
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
//创建请求
// NSURLRequest * request = [NSURLRequest requestWithURL:url];
//创建Session
NSURLSession * session = [NSURLSession sharedSession];
//创建任务
NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
//开启网络任务
[task resume];
  • 第二种网络请求方法
//创建URL
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
//创建请求
NSURLRequest * request = [NSURLRequest requestWithURL:url];
//创建Session
NSURLSession * session = [NSURLSession sharedSession];
//创建任务
NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }];
//开启网络任务
[task resume];
  • POST请求
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php"];

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

    //设置请求方法
request.HTTPMethod = @"POST"; //设置请求体
request.HTTPBody = [@"username=haha&password=123" dataUsingEncoding:NSUTF8StringEncoding]; [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }] resume];
  • 下载文件
    NSURL * url = [NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSURLSession * session = [NSURLSession sharedSession];

    NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        //location 下载到沙盒的地址
NSLog(@"下载完成%@",location); //response.suggestedFilename 响应信息中的资源文件名
NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename]; NSLog(@"缓存地址%@",cachesPath); //获取文件管理器
NSFileManager * mgr = [NSFileManager defaultManager];
//将临时文件移动到缓存目录下
//[NSURL fileURLWithPath:cachesPath] 将本地路径转化为URL类型
//URL如果地址不正确,生成的url对象为空 [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; }]; [downloadTask resume];

2.NSURLSession代理

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    //  全局session
// NSURLSession * session = [NSURLSession sharedSession];
//创建自定义session
//NSURLSessionConfiguration 的 配置
//[[NSOperationQueue alloc] init] 也可以写成 nil NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"]; NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSURLSessionDataTask * task = [session dataTaskWithURL:url]; [task resume]; } //接收到服务器响应 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { NSLog(@"%s",__FUNCTION__); //允许接受服务器回传数据
completionHandler(NSURLSessionResponseAllow);
} //接收服务器回传的数据,有可能执行多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} //请求成功或失败
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error);
}

3.NSURLSession大文件下载

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. NSLog(@"%@",NSSearchPathForDirectoriesInDomains(, , ));
} - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSURLSessionDownloadTask * task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [task resume]; } /* 监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次 bytesWritten 单次写入多少
totalBytesWritten 已经写入了多少
totalBytesExpectedToWrite 文件总大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //打印下载百分比
NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite); } //下载完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location { NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error);
}

4.NSURLSession断点续传

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>

@property (nonatomic, strong) NSURLSessionDownloadTask * task;

@property (nonatomic, strong) NSData * resumeData;

@property (nonatomic, strong) NSURLSession * session;

@end

@implementation ViewController

//故事板中开始按钮的响应方法
- (IBAction)start:(id)sender { NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; self.session = session; self.task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.68/丁香花.mp3"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [self.task resume];
} //故事板中暂停按钮的响应方法
- (IBAction)pause:(id)sender { //暂停就是将任务挂起 [self.task cancelByProducingResumeData:^(NSData *resumeData) {
//保存已下载的数据 self.resumeData = resumeData;
}];
}
//继续按钮的响应方法
- (IBAction)resume:(id)sender { //可以使用ResumeData创建任务 self.task = [self.session downloadTaskWithResumeData:self.resumeData]; //开启继续下载
[self.task resume]; } - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. NSLog(@"%@",NSSearchPathForDirectoriesInDomains(, , ));
} /* 监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次 bytesWritten 单次写入多少
totalBytesWritten 已经写入了多少
totalBytesExpectedToWrite 文件总大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //打印下载百分比
NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite); } //下载完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location { NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error);
}

NSURLSession详解的更多相关文章

  1. iOS开发——网络编程Swift篇&(七)NSURLSession详解

    NSURLSession详解 // MARK: - /* 使用NSURLSessionDataTask加载数据 */ func sessionLoadData() { //创建NSURL对象 var ...

  2. iOS开发-NSURLSession详解

    Core Foundation中NSURLConnection在2003年伴随着Safari浏览器的发行,诞生的时间比较久远,iOS升级比较快,AFNetWorking在3.0版本删除了所有基于NSU ...

  3. iOS7新特性-NSURLSession详解

    前言:本文由DevDiv版主@jas 原创翻译,转载请注明出处!原文:http://www.shinobicontrols.com/b ... day-1-nsurlsession/ 大家都知道,过去 ...

  4. AFNetworking 与 UIKit+AFNetworking 详解

    资料来源 : http://github.ibireme.com/github/list/ios GitHub : 链接地址 简介 : A delightful iOS and OS X networ ...

  5. CocoaPods详解之(二)----进阶篇

    CocoaPods详解之----进阶篇 作者:wangzz 原文地址:http://blog.csdn.net/wzzvictory/article/details/19178709 转载请注明出处 ...

  6. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

  7. 架构设计:远程调用服务架构设计及zookeeper技术详解(下篇)

    一.下篇开头的废话 终于开写下篇了,这也是我写远程调用框架的第三篇文章,前两篇都被博客园作为[编辑推荐]的文章,很兴奋哦,嘿嘿~~~~,本人是个很臭美的人,一定得要截图为证: 今天是2014年的第一天 ...

  8. EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解

    前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...

  9. Java 字符串格式化详解

    Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...

随机推荐

  1. 我为NET狂官方面试题-数据库篇答案

    题目:http://www.cnblogs.com/dunitian/p/6028838.html 汇总:http://www.cnblogs.com/dunitian/p/5977425.html ...

  2. 【WCF】自定义错误处理(IErrorHandler接口的用法)

    当被调用的服务操作发生异常时,可以直接把异常的原始内容传回给客户端.在WCF中,服务器传回客户端的异常,通常会使用 FaultException,该异常由这么几个东东组成: 1.Action:在服务调 ...

  3. CentOS7 重置root密码

    1- 在启动grub菜单,选择编辑选项启动 2 - 按键盘e键,来进入编辑界面 3 - 找到Linux 16的那一行,将ro改为rw init=/sysroot/bin/sh 4 - 现在按下 Con ...

  4. AJAX 大全

    本章内容: 简介 伪 AJAX 原生 AJAX XmlHttpRequest 的属性.方法.跨浏览器支持 jQuery AJAX 常用方法 跨域 AJAX JsonP CORS 简单请求.复制请求.请 ...

  5. Java开发中的23种设计模式详解

    [放弃了原文访问者模式的Demo,自己写了一个新使用场景的Demo,加上了自己的理解] [源码地址:https://github.com/leon66666/DesignPattern] 一.设计模式 ...

  6. 我理解的MVC

    前言 前一阶段对MVC模式及其衍生模式做了一番比较深入的研究和实践,这篇文章也算是一个阶段性的回顾和总结. 经典MVC模式 经典MVC模式中,M是指业务模型,V是指用户界面,C则是控制器,使用MVC的 ...

  7. Javascript 严格模式详解

    转自http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html 一.概述 除了正常运行模式,ECMAscript 5添加了第二 ...

  8. Oracle-BPM安装详解

    H3 BPM安装包括两个部分,基础工作包括安装IIS..net Freamwork基础框架.安装完成之后,主要配置安装包括数据库,H3 BPM 程序.下面详细介绍Oracle与H3 BPM对接安装的整 ...

  9. RMS去除在线认证

    在微软 OS 平台创建打开 RMS 文档如何避免时延 相信我们在企业内部的环境中已经部署了微软最新的OS平台,Windows 7和Windows 2008 R2,在这些OS平台上使用IRM功能时,您有 ...

  10. MongoDB学习笔记六—查询下

    查询内嵌文档 数据准备 > db.blog.find().pretty() { "_id" : ObjectId("585694e4c5b0525a48a441b5 ...