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分析的整体的思路,然后呢我以后的博客会按照这个内容更新,希望大家关注. 言归正传, ...
随机推荐
- [PHP] ubuntu16.04配置Lamp环境(搭建linux+apache+mysql+php7环境)
reference : http://blog.csdn.net/Abyss_sliver/article/details/77621404 好久没有在Linux环境下进行开发了,比较常用的还是win ...
- 实现Hadoop的Writable接口Implementing Writable interface of Hadoop
As we saw in the previous posts, Hadoop makes an heavy use of network transmissions for executing it ...
- iOS:UITableViewCell自定义单元格
UITableViewCell:自定义的单元格,可以在xib中创建单元格,也可以在storyBorad中创建单元格.有四种创建方式 <1>在storyBorad中创建的单元格,它是静态的单 ...
- iOS:NSDate的主要几种时间形式
NSDate:时间的获取和操作 1.获取当前时间 //获取当前日期 NSDate *date = sender.date; NSLog(@"%@",date); 2.将date转换 ...
- libjson 编译和使用 - 1. 编译
以下转自:http://blog.csdn.net/laogong5i0/article/details/8212511 最近想用box2dEdit来编辑一下比较复杂的图形然后倒入到自己有游戏里,但b ...
- Informatica 常用组件Lookup之六 查询
PowerCenter 基于您在查找转换中配置的端口和属性来查询查找.当第一行输入到查找转换时,PowerCenter 运行一个默认的 SQL 语句.如果使用关系查找,您可以在"查找 SQL ...
- android系统访问自己的tomcat服务器下的项目不能访问的原因
今天做android的一个下载功能,用自己机子上的tomcat做服务器,在tomcat上下载东西,可是android系统老是提示错误说不能连接到我的tomcat,可是我明明启动了tomcat服务啊,而 ...
- 遇到问题描述:Android Please ensure that adb is correctly located at问题解决
遇到问题描述: 运行android程序控制台输出 [2013-11-04 16:18:26 - ] The connection to adb is down, and a severe error ...
- Android下 使用百度地图sdk
百度地图 Android SDK是一套基于Android 2.1(v1.3.5及以前版本支持android 1.5以上系统)及以上版本设备的应用程序接口.可以使用该套 SDK开发适用于Android系 ...
- Windows批处理命令初了解
批处理文件时无格式的文本文件,它包含一条或多条命令.它的文件扩展名为.bat或.cmd.使用批处理文件可以简化日常重复性任务.其帮助:命令 /? eg:echo /? Ctrl+c组合键来强行终止一个 ...