实战iOS7之NSURLSession

NSURLSession VS NSURLConnection
NSURLSession可以看做是NSURLConnection的进化版,其对NSURLConnection的改进点有:

  • * 根据每个Session做配置(http header,Cache,Cookie,protocal,Credential),不再在整个App层面共享配置.

  • * 支持网络操作的取消和断点续传

  • * 改进了授权机制的处理

  • * 丰富的Delegate模型

  • * 分离了真实数据和网络配置数据。

  • * 后台处理上传和下载,即使你点击了“Home”按钮,后台仍然可以继续下载,并且提供了根据网络状况,电力情况进行处理的配置。


知识点

03154513_2RWj.png

用法
使用NSURLSession的一般套路如下:

  • 1. 定义一个NSURLRequest

  • 2. 定义一个NSURLSessionConfiguration,配置各种网络参数

  • 3. 使用NSURLSession的工厂方法获取一个所需类型的NSURLSession

  • 4. 使用定义好的NSURLRequest和NSURLSession构建一个NSURLSessionTask

  • 5. 使用Delegate或者CompletionHandler处理任务执行过程的所有事件。


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

03154513_ZTgg.gif

实现代码如下:

Object-c代码  收藏代码

  1. #import "UrlSessionDemoViewController.h"  

  2.   

  3. @interface UrlSessionDemoViewController ()  

  4.   

  5. @end  

  6.   

  7. @implementation UrlSessionDemoViewController  

  8.   

  9. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  

  10. {  

  11.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  

  12.     return self;  

  13. }  

  14.   

  15. - (void)viewDidLoad  

  16. {  

  17.     [super viewDidLoad];  

  18.     self.progressBar.progress = 0;  

  19. }  

  20.   

  21.   

  22. - (NSURLSession *)session  

  23. {  

  24.     //创建NSURLSession  

  25.     NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];  

  26.     NSURLSession  *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];  

  27.     return session;  

  28. }  

  29.   

  30. - (NSURLRequest *)request  

  31. {  

  32.     //创建请求  

  33.     NSURL *url = [NSURL URLWithString:@"http://p1.pichost.me/i/40/1639665.png"];  

  34.     NSURLRequest *request = [NSURLRequest requestWithURL:url];  

  35.     return request;  

  36. }  

  37.   

  38. -(IBAction)start:(id)sender  

  39. {  

  40.     //用NSURLSession和NSURLRequest创建网络任务  

  41.     self.task = [[self session] downloadTaskWithRequest:[self request]];  

  42.     [self.task resume];  

  43. }  

  44.   

  45. -(IBAction)pause:(id)sender  

  46. {  

  47.     NSLog(@"Pause download task");  

  48.     if (self.task) {  

  49.         //取消下载任务,把已下载数据存起来  

  50.         [self.task cancelByProducingResumeData:^(NSData *resumeData) {  

  51.             self.partialData = resumeData;  

  52.             self.task = nil;  

  53.         }];  

  54.     }  

  55. }  

  56.   

  57. -(IBAction)resume:(id)sender  

  58. {  

  59.     NSLog(@"resume download task");  

  60.     if (!self.task) {  

  61.         //判断是否又已下载数据,有的话就断点续传,没有就完全重新下载  

  62.         if (self.partialData) {  

  63.             self.task = [[self session] downloadTaskWithResumeData:self.partialData];  

  64.         }else{  

  65.             self.task = [[self session] downloadTaskWithRequest:[self request]];  

  66.         }  

  67.     }  

  68.     [self.task resume];  

  69. }  

  70.   

  71. //创建文件本地保存目录  

  72. -(NSURL *)createDirectoryForDownloadItemFromURL:(NSURL *)location  

  73. {  

  74.     NSFileManager *fileManager = [NSFileManager defaultManager];  

  75.     NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];  

  76.     NSURL *documentsDirectory = urls[0];  

  77.     return [documentsDirectory URLByAppendingPathComponent:[location lastPathComponent]];  

  78. }  

  79. //把文件拷贝到指定路径  

  80. -(BOOL) copyTempFileAtURL:(NSURL *)location toDestination:(NSURL *)destination  

  81. {  

  82.   

  83.     NSError *error;  

  84.     NSFileManager *fileManager = [NSFileManager defaultManager];  

  85.     [fileManager removeItemAtURL:destination error:NULL];  

  86.     [fileManager copyItemAtURL:location toURL:destination error:&error];  

  87.     if (error == nil) {  

  88.         return true;  

  89.     }else{  

  90.         NSLog(@"%@",error);  

  91.         return false;  

  92.     }  

  93. }  

  94.   

  95. #pragma mark NSURLSessionDownloadDelegate  

  96. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  

  97. didFinishDownloadingToURL:(NSURL *)location  

  98. {  

  99.     //下载成功后,文件是保存在一个临时目录的,需要开发者自己考到放置该文件的目录  

  100.     NSLog(@"Download success for URL: %@",location.description);  

  101.     NSURL *destination = [self createDirectoryForDownloadItemFromURL:location];  

  102.     BOOL success = [self copyTempFileAtURL:location toDestination:destination];  

  103.       

  104.     if(success){  

  105. //        文件保存成功后,使用GCD调用主线程把图片文件显示在UIImageView中  

  106.         dispatch_async(dispatch_get_main_queue(), ^{  

  107.             UIImage *image = [UIImage imageWithContentsOfFile:[destination path]];  

  108.             self.imageView.image = image;  

  109.             self.imageView.contentMode = UIViewContentModeScaleAspectFit;  

  110.             self.imageView.hidden = NO;  

  111.         });  

  112.     }else{  

  113.         NSLog(@"Meet error when copy file");  

  114.     }  

  115.     self.task = nil;  

  116. }  

  117.   

  118. /* Sent periodically to notify the delegate of download progress. */  

  119. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  

  120.       didWriteData:(int64_t)bytesWritten  

  121.  totalBytesWritten:(int64_t)totalBytesWritten  

  122. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite  

  123. {  

  124.     //刷新进度条的delegate方法,同样的,获取数据,调用主线程刷新UI  

  125.     double currentProgress = totalBytesWritten/(double)totalBytesExpectedToWrite;  

  126.     dispatch_async(dispatch_get_main_queue(), ^{  

  127.         self.progressBar.progress = currentProgress;  

  128.         self.progressBar.hidden = NO;  

  129.     });  

  130. }  

  131.   

  132. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  

  133.  didResumeAtOffset:(int64_t)fileOffset  

  134. expectedTotalBytes:(int64_t)expectedTotalBytes  

  135. {  

  136. }  

  137.   

  138. - (void)didReceiveMemoryWarning  

  139. {  

  140.     [super didReceiveMemoryWarning];  

  141. }  

  142.   

  143. @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

转载于:https://my.oschina.net/famiove/blog/500916

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值