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分析的整体的思路,然后呢我以后的博客会按照这个内容更新,希望大家关注. 言归正传, ...
随机推荐
- coursera课程Text Retrieval and Search Engines之Week 1 Overview
Week 1 OverviewHelp Center Week 1 On this page: Instructional Activities Time Goals and Objectives K ...
- The 12 Most Controversial Facts In Mathematics
Walter Hickey / BI Walter Hickey/BI Walter Hickey/BI Walter Hickey/BI Walter Hickey/BI Walter Hickey ...
- json的好处-新一代数据传输利器
JSON是一种轻量级的数据交换格式!和xml一样. 为什么不XML XML的冗余太大,不过XML阅读起来比较方面,所以并没有被json完全取代,很多时候都是并存.比如sina微博的开发平台有一个JSO ...
- 3维DEMO: 抽奖圆盘
抽奖圆盘 前些日子去超市,消费满一定钱数可以参加抽奖,就是在电视机上有个可旋转的圆盘,按一键开始,按一键抽奖结束.看到最大奖的扇形区域大约有个10度角的样子,按说中大奖的概率应该是36分之1.当然,这 ...
- OTL使用指南
1 OTL简介 OTL 是 Oracle, Odbcand DB2-CLI Template Library 的缩写,是一个C++编译中操控关系数据库的模板库,它目前几乎支持当前所有的各种主流数据库, ...
- Best Time to Buy and Sell Stock leetcode java
题目: Say you have an array for which the ith element is the price of a given stock on day i. If you w ...
- spring cloud-给Eureka Server加上安全的用户认证
前言 在前面的一篇文章中 spring cloud中启动Eureka Server 我们启动了Eureka Server,然后在浏览器中输入http://localhost:8761/后,直接回车,就 ...
- VUE性能优化总结
1.v-show,v-if 用哪个? 在我来看要分两个维度去思考问题: 第一个维度是权限问题,只要涉及到权限相关的展示无疑要用 v-if, 第二个维度在没有权限限制下根据用户点击的频次选择,频繁切换的 ...
- 直接修改class文件内容即使是文本会导致App异常,正确方式是修改java再用生成的class替换掉原有的class
前几天来了个小任务,把某项目中某人的邮件地址改了下. 由于对项目不熟悉,于是采用find方式找出app中所有包含某人邮件地址的文件都找出来了. xml,properties大约三四个,还有两个clas ...
- listView/GridView getChild获取不到的解决方法
在onCreate或onResume中调用了getChildAt()方法,这时候adapter中的Item还没有放入到AdapterView中去.... 解决方法,当activity获得焦点事件的时候 ...