实战iOS7之NSURLSession
NSURLSession VS NSURLConnection
NSURLSession可以看做是NSURLConnection的进化版,其对NSURLConnection的改进点有:
- * 根据每个Session做配置(http header,Cache,Cookie,protocal,Credential),不再在整个App层面共享配置.
- * 支持网络操作的取消和断点续传
- * 改进了授权机制的处理
- * 丰富的Delegate模型
- * 分离了真实数据和网络配置数据。
- * 后台处理上传和下载,即使你点击了“Home”按钮,后台仍然可以继续下载,并且提供了根据网络状况,电力情况进行处理的配置。
知识点

用法
使用NSURLSession的一般套路如下:
- 1. 定义一个NSURLRequest
- 2. 定义一个NSURLSessionConfiguration,配置各种网络参数
- 3. 使用NSURLSession的工厂方法获取一个所需类型的NSURLSession
- 4. 使用定义好的NSURLRequest和NSURLSession构建一个NSURLSessionTask
- 5. 使用Delegate或者CompletionHandler处理任务执行过程的所有事件。
实战
这儿我简单的实现了一个下载任务的断点续传功能,具体效果如下:

实现代码如下:
- #import "UrlSessionDemoViewController.h"
- @interface UrlSessionDemoViewController ()
- @end
- @implementation UrlSessionDemoViewController
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- return self;
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- self.progressBar.progress = 0;
- }
- - (NSURLSession *)session
- {
- //创建NSURLSession
- NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
- NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
- return session;
- }
- - (NSURLRequest *)request
- {
- //创建请求
- NSURL *url = [NSURL URLWithString:@"http://p1.pichost.me/i/40/1639665.png"];
- NSURLRequest *request = [NSURLRequest requestWithURL:url];
- return request;
- }
- -(IBAction)start:(id)sender
- {
- //用NSURLSession和NSURLRequest创建网络任务
- self.task = [[self session] downloadTaskWithRequest:[self request]];
- [self.task resume];
- }
- -(IBAction)pause:(id)sender
- {
- NSLog(@"Pause download task");
- if (self.task) {
- //取消下载任务,把已下载数据存起来
- [self.task cancelByProducingResumeData:^(NSData *resumeData) {
- self.partialData = resumeData;
- self.task = nil;
- }];
- }
- }
- -(IBAction)resume:(id)sender
- {
- NSLog(@"resume download task");
- if (!self.task) {
- //判断是否又已下载数据,有的话就断点续传,没有就完全重新下载
- if (self.partialData) {
- self.task = [[self session] downloadTaskWithResumeData:self.partialData];
- }else{
- self.task = [[self session] downloadTaskWithRequest:[self request]];
- }
- }
- [self.task resume];
- }
- //创建文件本地保存目录
- -(NSURL *)createDirectoryForDownloadItemFromURL:(NSURL *)location
- {
- NSFileManager *fileManager = [NSFileManager defaultManager];
- NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
- NSURL *documentsDirectory = urls[0];
- return [documentsDirectory URLByAppendingPathComponent:[location lastPathComponent]];
- }
- //把文件拷贝到指定路径
- -(BOOL) copyTempFileAtURL:(NSURL *)location toDestination:(NSURL *)destination
- {
- NSError *error;
- NSFileManager *fileManager = [NSFileManager defaultManager];
- [fileManager removeItemAtURL:destination error:NULL];
- [fileManager copyItemAtURL:location toURL:destination error:&error];
- if (error == nil) {
- return true;
- }else{
- NSLog(@"%@",error);
- return false;
- }
- }
- #pragma mark NSURLSessionDownloadDelegate
- - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
- didFinishDownloadingToURL:(NSURL *)location
- {
- //下载成功后,文件是保存在一个临时目录的,需要开发者自己考到放置该文件的目录
- NSLog(@"Download success for URL: %@",location.description);
- NSURL *destination = [self createDirectoryForDownloadItemFromURL:location];
- BOOL success = [self copyTempFileAtURL:location toDestination:destination];
- if(success){
- // 文件保存成功后,使用GCD调用主线程把图片文件显示在UIImageView中
- dispatch_async(dispatch_get_main_queue(), ^{
- UIImage *image = [UIImage imageWithContentsOfFile:[destination path]];
- self.imageView.image = image;
- self.imageView.contentMode = UIViewContentModeScaleAspectFit;
- self.imageView.hidden = NO;
- });
- }else{
- NSLog(@"Meet error when copy file");
- }
- self.task = nil;
- }
- /* Sent periodically to notify the delegate of download progress. */
- - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
- didWriteData:(int64_t)bytesWritten
- totalBytesWritten:(int64_t)totalBytesWritten
- totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
- {
- //刷新进度条的delegate方法,同样的,获取数据,调用主线程刷新UI
- double currentProgress = totalBytesWritten/(double)totalBytesExpectedToWrite;
- dispatch_async(dispatch_get_main_queue(), ^{
- self.progressBar.progress = currentProgress;
- self.progressBar.hidden = NO;
- });
- }
- - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
- didResumeAtOffset:(int64_t)fileOffset
- expectedTotalBytes:(int64_t)expectedTotalBytes
- {
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- }
- @end
所有代码在这儿:https://github.com/xianlinbox/iOS7_New/tree/master/iOS7_New/NSURLSession/ViewController
参考文章:http://www.objc.io/issue-5/from-nsurlconnection-to-nsurlsession.html
http://www.shinobicontrols.com/blog/posts/2013/09/20/ios7-day-by-day-day-1-nsurlsession
实战iOS7之NSURLSession的更多相关文章
- WWDC 2013 Session笔记 - iOS7中的多任务
这是我的WWDC2013系列笔记中的一篇,完整的笔记列表请参看这篇总览.本文仅作为个人记录使用,也欢迎在许可协议范围内转载或使用,但是还烦请保留原文链接,谢谢您的理解合作.如果您觉得本站对您能有帮助, ...
- ios7中的多任务
转自:http://onevcat.com/2013/08/ios7-background-multitask/ WWDC 2013 Session笔记 - iOS7中的多任务 iOS7的后台多任务特 ...
- NSURLSession的使用
虽然在iOS7引入NSURLSession时,就知道NSURLConnection会最终被苹果放弃,但人总是喜欢做熟悉的事情,在NSURLConnection还可以使用时,就懒得学习这新玩意了,而且本 ...
- 【从零学习openCV】IOS7下的人脸检測
前言: 人脸检測与识别一直是计算机视觉领域一大热门研究方向,并且也从安全监控等工业级的应用扩展到了手机移动端的app,总之随着人脸识别技术获得突破,其应用前景和市场价值都是不可估量的,眼下在学习ope ...
- 【从零学习openCV】IOS7根据人脸检测
前言: 人脸检測与识别一直是计算机视觉领域一大热门研究方向,并且也从安全监控等工业级的应用扩展到了手机移动端的app.总之随着人脸识别技术获得突破,其应用前景和市场价值都是不可估量的,眼下在学习ope ...
- [ios-必看] WWDC 2013 Session笔记 - iOS7中的多任务【转】
感谢:http://onevcat.com/2013/08/ios7-background-multitask/ http://www.objc.io/issue-5/multitasking.htm ...
- iOS7中的多任务 - Background Fetch,Silent Remote Notifications,Background Transfer Service
转自:http://onevcat.com/2013/08/ios7-background-multitask/ 在IOS 7 出来不就,公司内部也组织了一次关于IOS 7 特性的的分享,今天看见on ...
- iOS 多任务
本文转自猫神的博客:https://onevcat.com/2013/08/ios7-background-multitask/ 写的没的说,分享给大家,一起学习! iOS7以前的Multitaski ...
- GitHub上有很多不错的iOS开源项目
GitHub上有很多不错的iOS开源项目,个人认为不错的,有这么几个:1. ReactiveCocoa:ReactiveCocoa/ReactiveCocoa · GitHub:GitHub自家的函数 ...
随机推荐
- Asp .net core api+Entity Framework core 实现数据CRUD数据库中(附Git地址)
最近在学dotNetCore 所以尝试了一下api 这个功能 不多说了大致实现如下 1.用vs2017建立一个Asp.net Core Web 应用程序 在弹出的对话框中选择 Web API 项目名 ...
- 数据库执行的时候报ORA-01653错误
查明原因是因为表空间文件到达了32G,因为oracle11g单个表空间大于32G的时候就不会自动在扩展了于是需要增加新的表空间文件,下面是4种解决此问题的方法 Meathod1:给表空间增加数据文件 ...
- c++ 中介者模式(mediator)
中介者模式:用一个中介对象来封装一系列的对象交互.中介者使各个对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互.中介者模式的例子很多,大到联合国安理会,小到房屋中介.下面以 ...
- controller,service,repository,component注解的使用对比
项目中的controller层使用@controller注解 @Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象.分发处理器将会扫描使用了 ...
- HTML ISO-8859-1 参考手册(html字符转义)
HTML 4.01 支持 ISO 8859-1 (Latin-1) 字符集. ISO-8859-1 的较低部分(从 1 到 127 之间的代码)是最初的 7 比特 ASCII. ISO-8859-1 ...
- 44. Wildcard Matching 有简写的字符串匹配
[抄题]: Given an input string (s) and a pattern (p), implement wildcard pattern matching with support ...
- 276. Paint Fence篱笆涂色
[抄题]: There is a fence with n posts, each post can be painted with one of the k colors. You have to ...
- GRUB使用说明
从Red Hat Linux 7.2起,GRUB(GRand Unified Bootloader)取代LILO成为了默认的启动装载程序.相信LILO对于大家来说都是很熟悉的.这次Red Hat Li ...
- 创建一个实例&创建一个线程。。
using System; using System.Threading; namespace WorkerThread02 { class ThreadTest { bool done; stati ...
- 1.spark的wordcount解析
一.Eclipse(scala IDE)开发local和cluster (一). 配置开发环境 要在本地安装好java和scala. 由于spark1.6需要scala 2.10.X版本的.推荐 2 ...