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处理任务执行过程的所有事件。

实战 
这儿我简单的实现了一个下载任务的断点续传功能,具体效果如下:

实现代码如下:

  1. #import "UrlSessionDemoViewController.h"
  2. @interface UrlSessionDemoViewController ()
  3. @end
  4. @implementation UrlSessionDemoViewController
  5. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  6. {
  7. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  8. return self;
  9. }
  10. - (void)viewDidLoad
  11. {
  12. [super viewDidLoad];
  13. self.progressBar.progress = 0;
  14. }
  15. - (NSURLSession *)session
  16. {
  17. //创建NSURLSession
  18. NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
  19. NSURLSession  *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
  20. return session;
  21. }
  22. - (NSURLRequest *)request
  23. {
  24. //创建请求
  25. NSURL *url = [NSURL URLWithString:@"http://p1.pichost.me/i/40/1639665.png"];
  26. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  27. return request;
  28. }
  29. -(IBAction)start:(id)sender
  30. {
  31. //用NSURLSession和NSURLRequest创建网络任务
  32. self.task = [[self session] downloadTaskWithRequest:[self request]];
  33. [self.task resume];
  34. }
  35. -(IBAction)pause:(id)sender
  36. {
  37. NSLog(@"Pause download task");
  38. if (self.task) {
  39. //取消下载任务,把已下载数据存起来
  40. [self.task cancelByProducingResumeData:^(NSData *resumeData) {
  41. self.partialData = resumeData;
  42. self.task = nil;
  43. }];
  44. }
  45. }
  46. -(IBAction)resume:(id)sender
  47. {
  48. NSLog(@"resume download task");
  49. if (!self.task) {
  50. //判断是否又已下载数据,有的话就断点续传,没有就完全重新下载
  51. if (self.partialData) {
  52. self.task = [[self session] downloadTaskWithResumeData:self.partialData];
  53. }else{
  54. self.task = [[self session] downloadTaskWithRequest:[self request]];
  55. }
  56. }
  57. [self.task resume];
  58. }
  59. //创建文件本地保存目录
  60. -(NSURL *)createDirectoryForDownloadItemFromURL:(NSURL *)location
  61. {
  62. NSFileManager *fileManager = [NSFileManager defaultManager];
  63. NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
  64. NSURL *documentsDirectory = urls[0];
  65. return [documentsDirectory URLByAppendingPathComponent:[location lastPathComponent]];
  66. }
  67. //把文件拷贝到指定路径
  68. -(BOOL) copyTempFileAtURL:(NSURL *)location toDestination:(NSURL *)destination
  69. {
  70. NSError *error;
  71. NSFileManager *fileManager = [NSFileManager defaultManager];
  72. [fileManager removeItemAtURL:destination error:NULL];
  73. [fileManager copyItemAtURL:location toURL:destination error:&error];
  74. if (error == nil) {
  75. return true;
  76. }else{
  77. NSLog(@"%@",error);
  78. return false;
  79. }
  80. }
  81. #pragma mark NSURLSessionDownloadDelegate
  82. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
  83. didFinishDownloadingToURL:(NSURL *)location
  84. {
  85. //下载成功后,文件是保存在一个临时目录的,需要开发者自己考到放置该文件的目录
  86. NSLog(@"Download success for URL: %@",location.description);
  87. NSURL *destination = [self createDirectoryForDownloadItemFromURL:location];
  88. BOOL success = [self copyTempFileAtURL:location toDestination:destination];
  89. if(success){
  90. //        文件保存成功后,使用GCD调用主线程把图片文件显示在UIImageView中
  91. dispatch_async(dispatch_get_main_queue(), ^{
  92. UIImage *image = [UIImage imageWithContentsOfFile:[destination path]];
  93. self.imageView.image = image;
  94. self.imageView.contentMode = UIViewContentModeScaleAspectFit;
  95. self.imageView.hidden = NO;
  96. });
  97. }else{
  98. NSLog(@"Meet error when copy file");
  99. }
  100. self.task = nil;
  101. }
  102. /* Sent periodically to notify the delegate of download progress. */
  103. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
  104. didWriteData:(int64_t)bytesWritten
  105. totalBytesWritten:(int64_t)totalBytesWritten
  106. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  107. {
  108. //刷新进度条的delegate方法,同样的,获取数据,调用主线程刷新UI
  109. double currentProgress = totalBytesWritten/(double)totalBytesExpectedToWrite;
  110. dispatch_async(dispatch_get_main_queue(), ^{
  111. self.progressBar.progress = currentProgress;
  112. self.progressBar.hidden = NO;
  113. });
  114. }
  115. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
  116. didResumeAtOffset:(int64_t)fileOffset
  117. expectedTotalBytes:(int64_t)expectedTotalBytes
  118. {
  119. }
  120. - (void)didReceiveMemoryWarning
  121. {
  122. [super didReceiveMemoryWarning];
  123. }
  124. @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的更多相关文章

  1. WWDC 2013 Session笔记 - iOS7中的多任务

    这是我的WWDC2013系列笔记中的一篇,完整的笔记列表请参看这篇总览.本文仅作为个人记录使用,也欢迎在许可协议范围内转载或使用,但是还烦请保留原文链接,谢谢您的理解合作.如果您觉得本站对您能有帮助, ...

  2. ios7中的多任务

    转自:http://onevcat.com/2013/08/ios7-background-multitask/ WWDC 2013 Session笔记 - iOS7中的多任务 iOS7的后台多任务特 ...

  3. NSURLSession的使用

    虽然在iOS7引入NSURLSession时,就知道NSURLConnection会最终被苹果放弃,但人总是喜欢做熟悉的事情,在NSURLConnection还可以使用时,就懒得学习这新玩意了,而且本 ...

  4. 【从零学习openCV】IOS7下的人脸检測

    前言: 人脸检測与识别一直是计算机视觉领域一大热门研究方向,并且也从安全监控等工业级的应用扩展到了手机移动端的app,总之随着人脸识别技术获得突破,其应用前景和市场价值都是不可估量的,眼下在学习ope ...

  5. 【从零学习openCV】IOS7根据人脸检测

    前言: 人脸检測与识别一直是计算机视觉领域一大热门研究方向,并且也从安全监控等工业级的应用扩展到了手机移动端的app.总之随着人脸识别技术获得突破,其应用前景和市场价值都是不可估量的,眼下在学习ope ...

  6. [ios-必看] WWDC 2013 Session笔记 - iOS7中的多任务【转】

    感谢:http://onevcat.com/2013/08/ios7-background-multitask/ http://www.objc.io/issue-5/multitasking.htm ...

  7. iOS7中的多任务 - Background Fetch,Silent Remote Notifications,Background Transfer Service

    转自:http://onevcat.com/2013/08/ios7-background-multitask/ 在IOS 7 出来不就,公司内部也组织了一次关于IOS 7 特性的的分享,今天看见on ...

  8. iOS 多任务

    本文转自猫神的博客:https://onevcat.com/2013/08/ios7-background-multitask/ 写的没的说,分享给大家,一起学习! iOS7以前的Multitaski ...

  9. GitHub上有很多不错的iOS开源项目

    GitHub上有很多不错的iOS开源项目,个人认为不错的,有这么几个:1. ReactiveCocoa:ReactiveCocoa/ReactiveCocoa · GitHub:GitHub自家的函数 ...

随机推荐

  1. avalon1.3的新特性预览

    avalon1.2的性能优化风暴很快就告一段落,入职也快一个月了,许多乱七八糟的事也少了下来,估计未来一个月会有许多好东呈现给大家. 首先是一个性能检测工具.由于MVVM是将原本由人脑干的事,转到各种 ...

  2. KVM镜像image 转换 调整

    qemu-img create -f raw test.raw 8G 创建一个raw格式,大小为8G的镜像. qemu-img info disk1.qcow2     #查看镜像大小及实际占用多少空 ...

  3. Sqoop 1.99.6 安装和使用

        安装   1.安装准备工作:   下载的sqoop安装包 http://mirrors.hust.edu.cn/apache/sqoop/1.99.6/sqoop-1.99.6.tar.gz ...

  4. HttpServletResponse返回页面弹窗

    下载方法: @RequestMapping(value = "/download.htm") public void downLoadFile(String id,HttpServ ...

  5. default of c#

    [default of c#] 在泛型类和泛型方法中产生的一个问题是,在预先未知以下情况时,如何将默认值分配给参数化类型 T: T 是引用类型还是值类型. 如果 T 为值类型,则它是数值还是结构. 给 ...

  6. cf499B-Lecture 【map】

    http://codeforces.com/problemset/problem/499/B B. Lecture     You have a new professor of graph theo ...

  7. vagrant 安装与配置

    1.下载vagrant的安装包 http://downloads.vagrantup.com/ 2.解压安装 3.安装box环境   4.安装成功显示 5.提示要安装virbox

  8. Linux分区挂载点介绍

    一.Linux分区挂载点介绍 Linux分区挂载点介绍,推荐容量仅供参考不是绝对,跟各系统用途以及硬盘空间配额等因素实际调整: 分区类型 介绍 备注 /boot 启动分区 一般设置100M-200M, ...

  9. c++ static笔记

    [转]http://www.cnblogs.com/zi-xing/p/4590282.html static的作用 在函数体,一个被声明为static的变量,在这一函数被调用的过程里,其数值维持不变 ...

  10. Auto Encoder

    对自编码器的理解: 对于给定的原始输入x,让网络自动找到一种编码方式(特征提取,原始数据的另一种表达),使其解码后的输出x'尽可能复现原始输入x. 知乎参考:https://www.zhihu.com ...