ios NSURLSession使用说明及后台工作流程分析
NSURLSession是iOS7中新的网络接口,它与咱们熟悉的NSURLConnection是并列的。在程序在前台时,NSURLSession与NSURLConnection可以互为替代工作。注意,如果用户强制将程序关闭,NSURLSession会断掉。

- @implementation APLAppDelegate
- - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier
- completionHandler:(void (^)())completionHandler
- {
- BLog();
- /*
- Store the completion handler. The completion handler is invoked by the view controller's checkForAllDownloadsHavingCompleted method (if all the download tasks have been completed).
- */
- self.backgroundSessionCompletionHandler = completionHandler;
- }
- //……
- @end
- //Session的Delegate
- @implementation APLViewController
- - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
- {
- APLAppDelegate *appDelegate = (APLAppDelegate *)[[UIApplication sharedApplication] delegate];
- if (appDelegate.backgroundSessionCompletionHandler) {
- void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
- appDelegate.backgroundSessionCompletionHandler = nil;
- completionHandler();
- }
- NSLog(@"All tasks are finished");
- }
- @end
- //////////////////////
代码演示
- //
- // MJViewController.m
- // 01.URLSession 上传
- //
- // Created by apple on 14-4-30.
- // Copyright (c) 2014年 itcast. All rights reserved.
- //
- #import "MJViewController.h"
- @interface MJViewController () <NSURLSessionTaskDelegate>
- @end
- @implementation MJViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- [self uploadFile1];
- }
- #pragma mark - 监控上传进度
- - (void)uploadFile1
- {
- // 1. URL
- NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"head8.png" withExtension:nil];
- NSURL *url = [NSURL URLWithString:@"http://localhost/uploads/1.png"];
- // 2. Request
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
- // 1> PUT方法
- // PUT
- // 1) 文件大小无限制
- // 2) 可以覆盖文件
- // POST
- // 1) 通常有限制2M
- // 2) 新建文件,不能重名
- request.HTTPMethod = @"PUT";
- // 2> 安全认证
- // admin:123456
- // result base64编码
- // Basic result
- /**
- BASE 64是网络传输中最常用的编码格式 - 用来将二进制的数据编码成字符串的编码方式
- BASE 64的用法:
- 1> 能够编码,能够解码
- 2> 被很多的加密算法作为基础算法
- */
- NSString *authStr = @"admin:123456";
- NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
- NSString *base64Str = [authData base64EncodedStringWithOptions:0];
- NSString *resultStr = [NSString stringWithFormat:@"Basic %@", base64Str];
- [request setValue:resultStr forHTTPHeaderField:@"Authorization"];
- // 3. Session,全局单例(我们能够给全局的session设置代理吗?如果不能为什么?)
- // sharedSession是全局共享的,因此如果要设置代理,需要单独实例化一个Session
- /**
- NSURLSessionConfiguration(会话配置)
- defaultSessionConfiguration; // 磁盘缓存,适用于大的文件上传下载
- ephemeralSessionConfiguration; // 内存缓存,以用于小的文件交互,GET一个头像
- backgroundSessionConfiguration:(NSString *)identifier; // 后台上传和下载
- */
- NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
- NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
- // 需要监听任务的执行状态
- NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:fileURL];
- // 4. resume
- [task resume];
- }
- #pragma mark - 上传进度的代理方法
- - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
- {
- // bytesSent totalBytesSent totalBytesExpectedToSend
- // 发送字节(本次发送的字节数) 总发送字节数(已经上传的字节数) 总希望要发送的字节(文件大小)
- NSLog(@"%lld-%lld-%lld-", bytesSent, totalBytesSent, totalBytesExpectedToSend);
- // 已经上传的百分比
- float progress = (float)totalBytesSent / totalBytesExpectedToSend;
- NSLog(@"%f", progress);
- }
- #pragma mark - 上传完成的代理方法
- - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
- {
- NSLog(@"完成 %@", [NSThread currentThread]);
- }
- @end
02.Session下载
- //
- // MJViewController.m
- // 02.Session下载
- //
- // Created by apple on 14-4-30.
- // Copyright (c) 2014年 itcast. All rights reserved.
- //
- #import "MJViewController.h"
- @interface MJViewController () <NSURLSessionDownloadDelegate>
- @property (weak, nonatomic) IBOutlet UIImageView *imageView;
- @end
- /**
- // 下载进度跟进
- - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
- didWriteData:(int64_t)bytesWritten
- totalBytesWritten:(int64_t)totalBytesWritten
- totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;
- didWriteData totalBytesWritten totalBytesExpectedToWrite
- 本次写入的字节数 已经写入的字节数 预期下载的文件大小
- // 完成下载
- - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
- didFinishDownloadingToURL:(NSURL *)location;
- */
- @implementation MJViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- [self downloadTask];
- }
- #pragma mark - 下载(GET)
- - (void)downloadTask
- {
- // 1. URL
- NSURL *url = [NSURL URLWithString:@"http://localhost/itcast/images/head1.png"];
- // 2. Request
- NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0];
- // 3. Session
- NSURLSession *session = [NSURLSession sharedSession];
- // 4. download
- [[session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
- // 下载的位置,沙盒中tmp目录中的临时文件,会被及时删除
- NSLog(@"下载完成 %@ %@", location, [NSThread currentThread]);
- /**
- document 备份,下载的文件不能放在此文件夹中
- cache 缓存的,不备份,重新启动不会被清空,如果缓存内容过多,可以考虑新建一条线程检查缓存目录中的文件大小,自动清理缓存,给用户节省控件
- tmp 临时,不备份,不缓存,重新启动iPhone,会自动清空
- */
- // 直接通过文件名就可以加载图像,图像会常驻内存,具体的销毁有系统负责
- // [UIImage imageNamed:@""];
- dispatch_async(dispatch_get_main_queue(), ^{
- // 从网络下载下来的是二进制数据
- NSData *data = [NSData dataWithContentsOfURL:location];
- // 这种方式的图像会自动释放,不占据内存,也不需要放在临时文件夹中缓存
- // 如果用户需要,可以提供一个功能,保存到用户的相册即可
- UIImage *image = [UIImage imageWithData:data];
- self.imageView.image = image;
- });
- }] resume];
- // [task resume];
- }
- @end
http://www.cocoachina.com/applenews/devnews/2013/1106/7304.html
ios NSURLSession使用说明及后台工作流程分析的更多相关文章
- NSURLSession使用说明及后台工作流程分析
原文摘自http://www.cocoachina.com/industry/20131106/7304.html NSURLSession是iOS7中新的网络接口,它与咱们熟悉的NSURLConne ...
- ios NSURLSession(iOS7后,取代NSURLConnection)使用说明及后台工作流程分析
NSURLSession是iOS7中新的网络接口,它与咱们熟悉的NSURLConnection是并列的.在程序在前台时,NSURLSession与NSURLConnection可以互为替代工作.注意, ...
- 【转】Hostapd工作流程分析
[转]Hostapd工作流程分析 转自:http://blog.chinaunix.net/uid-30081165-id-5290531.html Hostapd是一个运行在用户态的守护进程,可以通 ...
- 第2章 rsync算法原理和工作流程分析
本文通过示例详细分析rsync算法原理和rsync的工作流程,是对rsync官方技术报告和官方推荐文章的解释. 以下是本文的姊妹篇: 1.rsync(一):基本命令和用法 2.rsync(二):ino ...
- [国嵌笔记][030][U-Boot工作流程分析]
uboot工作流程分析 程序入口 1.打开顶层目录的Makefile,找到目标smdk2440_config的命令中的第三项(smdk2440) 2.进入目录board/samsung/smdk244 ...
- rsync算法原理和工作流程分析
本文通过示例详细分析rsync算法原理和rsync的工作流程,是对rsync官方技术报告和官方推荐文章的解释.本文不会介绍如何使用rsync命令(见rsync基本用法),而是详细解释它如何实现高效的增 ...
- nodejs的Express框架源码分析、工作流程分析
nodejs的Express框架源码分析.工作流程分析 1.Express的编写流程 2.Express关键api的使用及其作用分析 app.use(middleware); connect pack ...
- Mysql工作流程分析
Mysql工作流程图 工作流程分析 1. 所有的用户连接请求都先发往连接管理器 2. 连接管理器 (1)一直处于侦听状态 (2)用于侦听用户请求 3. 线程管理器 (1)因为每个用户 ...
- u-boot分析(二)----工作流程分析
u-boot分析(二) 由于这两天家里有点事,所以耽误了点时间,没有按时更新,今天我首先要跟大家说说我对于u-boot分析的整体的思路,然后呢我以后的博客会按照这个内容更新,希望大家关注. 言归正传, ...
随机推荐
- mysql访问权限GRANT ALL PRIVILEGES ON,访问权限表
开启远程连接:2, 修改 Mysql-Server 用户配置mysql> USE mysql; -- 切换到 mysql DBDatabase changedmysql> SELECT U ...
- [18] 螺旋楼梯(Spiral Stairs)图形的生成算法
顶点数据的生成 bool YfBuildSpiralStairsVertices ( Yreal radius, Yreal assistRadius, Yreal height, Yuint sli ...
- js移除Array中指定元素
首先需要找到元素的下标: var array = [2, 5, 9]; var index = array.indexOf(5); 使用splice函数进行移除: if (index > -1) ...
- PHPnow For ASP&&ASP.NET&&MongoDB&&MySQL支持VC6.0编译器&&MySQL升级
可能和大家熟悉的是LAMP,Linux+Apache+Mysql+PHP,在Windows上,可能大家比较熟悉的是WAMP,Windows+Apache+Mysql+PHP,这是一个集成环境,说到集成 ...
- 我对REST的理解
1:rest的由来 REST即表述性状态传递(英文:Representational State Transfer,简称REST) 通俗点说:资源在网络中以某种表现形式进行状态转移. 源于REST之父 ...
- 【Android】自己定义控件实现可滑动的开关(switch)
~转载请注明来源:http://blog.csdn.net/u013015161/article/details/46704745 介绍 昨天晚上写了一个Android的滑动开关, 即SlideSwi ...
- JS中关于in运算符的问题
转自:http://bbs.bccn.net/thread-412608-1-1.html in运算符 in运算符虽然也是一个二元运算符,但是对运算符左右两个操作数的要求比较严格.in运算符要求第1个 ...
- PHP经典项目案例-(一)博客管理系统5
本篇实现发表博客. 八.发表博客 (1).界面实现file.php <tr> <td colSpan=3 valign="baseline" style ...
- 如何使用Flash抓抓狂抓取网页Flash
运行该软件,如果把鼠标移动到flash的部位浏览器左边顶部没有出现保存按钮,则定位到这个Flash,右击选择播放,暂停,反复一次即可看到. 把flash暂停再播放即可. 如果是QQ空间的漂亮的背景,不 ...
- 【设计模式】学习笔记15:代理模式(Proxy Pattern)
本文出自 http://blog.csdn.net/shuangde800 本笔记内容: 1. JAVA远程代理调用(RMI) 2. 代理模式 走进代理模式 在上一篇的状态模式中,我们实现了一个糖 ...