【iOS】文件下载小记
下载文件到NSURLConnection与NSURLSession两种,一种有恨悠久的历史了。
使用相对麻烦,后者是新出来的,添加了一些额外的功能。
一、NSURLConnection实现下载
TIPS:
3、了解在NSURLConnection上加代理。
[consetDelegateQueue:[[NSOperationQueuealloc]init]]
下载时用得着.
下面程序实现追踪下载百分比的下载(URLConnection自带的方法):
#import "XNDownload.h" typedef void(^ProgressBlock)(float percent); @interface XNDownload() <NSURLConnectionDataDelegate> @property (nonatomic, strong) NSMutableData *dataM; // 保存在沙盒中的文件路径
@property (nonatomic, strong) NSString *cachePath;
// 文件总长度
@property (nonatomic, assign) long long fileLength;
// 当前下载的文件长度
@property (nonatomic, assign) long long currentLength; // 回调块代码
@property (nonatomic, copy) ProgressBlock progress; @end @implementation XNDownload - (NSMutableData *)dataM
{
if (!_dataM) {
_dataM = [NSMutableData data];
}
return _dataM;
} - (void)downloadWithURL:(NSURL *)url progress:(void (^)(float))progress
{
// 0. 记录块代码
self.progress = progress; // 1. request GET
NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2. connection
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; // 让connection支持多线程。指定代理的工作队列就可以
// NSURLConnection在执行时,执行循环不负责监听代理的详细执行
[connection setDelegateQueue:[[NSOperationQueue alloc] init]]; // 3. 启动连接
[connection start];
} #pragma mark - 代理方法
// 1. 接收到server的响应。server执行完请求,向client回传数据
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%@ %lld", response.suggestedFilename, response.expectedContentLength);
// 1. 保存的缓存路径
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
self.cachePath = [cachePath stringByAppendingPathComponent:response.suggestedFilename];
// 2. 文件总长度
self.fileLength = response.expectedContentLength;
// 3. 当前下载的文件长度
self.currentLength = 0; // 清空数据
[self.dataM setData:nil];
} // 2. 接收数据。从server接收到数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 拼接数据
[self.dataM appendData:data]; // 依据data的长度添加当前下载的文件长度
self.currentLength += data.length; float progress = (float)self.currentLength / self.fileLength; // 推断是否定义了块代码
if (self.progress) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// 强制执行循环执行一次更新
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate date]]; self.progress(progress);
}];
}
} // 3. 完毕接收
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%s %@", __func__, [NSThread currentThread]);
// 将dataM写入沙盒的缓存文件夹
// 写入数据,NSURLConnection底层实现是用磁盘做的缓存
[self.dataM writeToFile:self.cachePath atomically:YES];
} // 4. 出现错误
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@", error.localizedDescription);
} @end
二、NSURLSession实现下载
NSURLSession能实现断点续传,暂停下载等功能。
#import "XNViewController.h" @interface XNViewController () <NSURLSessionDownloadDelegate> // 下载网络回话
@property (nonatomic, strong) NSURLSession *session;
// 下载任务
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
// 续传的二进制数据
@property (nonatomic, strong) NSData *resumeData;
@end @implementation XNViewController - (NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
}
return _session;
} - (void)viewDidLoad
{
[super viewDidLoad]; [self downloadFile];
} // 暂停下载任务
- (IBAction)pause
{
// 假设下载任务不存在,直接返回
if (self.downloadTask == nil) return; // 暂停任务(块代码中的resumeData就是当前正在下载的二进制数据)
// 停止下载任务时,须要保存数据
[self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
self.resumeData = resumeData; // 清空而且释放当前的下载任务
self.downloadTask = nil;
}];
} - (IBAction)resume
{
// 要续传的数据是否存在?
if (self.resumeData == nil) return; // 建立续传的下载任务
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
[self.downloadTask resume]; // 将此前记录的续传数据清空
self.resumeData = nil;
} // 假设在开发中使用到缓存文件夹,一定要提供一个功能,“清除缓存”。
/** 下载文件 */
- (void)downloadFile
{
NSString *urlStr = @"http://localhost/苍老师全集.rmvb";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; // (1) 代理 & 直接启动任
// 2. 启动下载任务
self.downloadTask = [self.session downloadTaskWithURL:url]; [self.downloadTask resume];
} #pragma mark - 下载代理方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSLog(@"完毕 %@ %@", location, [NSThread currentThread]);
} /**
bytesWritten : 本次下载的字节数
totalBytesWritten : 已经下载的字节数
totalBytesExpectedToWrite : 下载总大小
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
float progress = (float)totalBytesWritten / totalBytesExpectedToWrite; [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//主线程中更新进度UI操作。。。。
}];
} /** 续传的代理方法 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
NSLog(@"offset : %lld", fileOffset);
} @end
出处:http://blog.csdn.net/xn4545945
版权声明:本文博主原创文章。博客,未经同意不得转载。
【iOS】文件下载小记的更多相关文章
- iOS 文件下载
iOS 视频音乐类等应用会用到“文件下载”.文件下载在iOS中的实现如下: 1.小文件下载 @interface ViewController () <NSURLConnectionDataDe ...
- IOS知识小记
iOS开发 小知识点 http://www.cnblogs.com/tangbinblog/archive/2012/07/20/2601324.html Objective-C中的instancet ...
- iOS 文件下载及断点续传
ios的下载我们可以使用的方法有:NSData.NSURLConnection.NSURLSession还有第三方框架AFNetworking和ASI 利用NSData方法和NSURLConnecti ...
- 【转】iOS 文件下载及断点续传
ios的下载我们可以使用的方法有:NSData.NSURLConnection.NSURLSession还有第三方框架AFNetworking和ASI 利用NSData方法和NSURLConnecti ...
- IOS开发小记-内存管理
关于IOS开发的内存管理的文章已经很多了,因此系统的知识点就不写了,这里我写点平时工作遇到的疑问以及解答做个总结吧,相信也会有人遇到相同的疑问呢,欢迎学习IOS的朋友请加ios技术交流群:190956 ...
- iOS 文件下载和打开
最近的项目要用到一个在线报告的下载,于是完成后自己在理一下思路,大体的实现了我要得需求. 话不多说,直接上代码 首先,取到网络文件的链接,进行判段是否需求再次下载还是直接打开 #pragma mark ...
- ios碎片小记
一.UIImageView 1.图片形状设为圆形时可能会由于图片的宽高比例导致显示出来的效果不是圆形 解决:设置UIImageView的contentMode为UIViewContentModeSca ...
- IOS文件下载
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, ...
- iOS - NetRequest 网络数据请求
1.网络请求 1.1 网络通讯三要素 1.IP 地址(主机名): 网络中设备的唯一标示.不易记忆,可以用主机名(域名). 1) IP V4: 0~255.0~255.0~255.0~255 ,共有 2 ...
随机推荐
- EXT2/EXT3文件系统(二)
整理自<鸟哥的Linux私房菜>,整理者:华科小涛http://www.cnblogs.com/hust-ghtao/ 接EXT2/EXT3文件系统(一): 2.3 Supe ...
- C++学习之路—多态性与虚函数(一)利用虚函数实现动态多态性
(根据<C++程序设计>(谭浩强)整理,整理者:华科小涛,@http://www.cnblogs.com/hust-ghtao转载请注明) 多态性是面向对象程序设计的一个重要特征.顾名思义 ...
- MSSQL - 自增1的标识列一次增长了1000
@情若天_RunUp: 1. Open "SQL Server Configuration Manager"2. Click "SQL Server Services&q ...
- 国际化之MessageFormat与占位符
如果一个字符串文本中包含了多个与国际化相关的数据,可以使用MessageFormat类对这些数据进行批量处理. 例如: 在2016年1月9日的时候,一场台风导致了500间房屋的摧毁和¥1000000元 ...
- 中间件(Middleware)
中间件(Middleware) ASP.NET Core开发,开发并使用中间件(Middleware). 中间件是被组装成一个应用程序管道来处理请求和响应的软件组件. 每个组件选择是否传递给管道中的下 ...
- vcredist_x86.exe 静默安装方法
我们打包基于VC++开发的应用程序,我们会一同打包一个VC运行库,否则安装到一些非开发环境中,你的应用程序依然可以正确运行. Visual C++ 2008 Redistributable Packa ...
- Problem K: Yikes -- Bikes!
http://acm.upc.edu.cn/problem.php?id=2780 昨天做的题,没过……!!!伤心……题意:给你n个单位,n-1组关系,让你单位换算……解题思路:Floyd算法自己听别 ...
- C#实现环形队列
概述 看了一个数据结构的教程,是用C++写的,可自己C#还是一个菜鸟,更别说C++了,但还是大胆尝试用C#将其中的环形队列的实现写出来,先上代码: public class MyQueue<T& ...
- UI编辑器
本篇教程通过制作捕鱼达人的启动界面来说明CocoStudio UI编辑器的用法.先看看效果图 好了,下面一步一步的动手做吧! 1.打开软件 2.新建项目 依次打开软件主界面左上角菜单栏的:“文件”-- ...
- 所有CN_消息的说明
Notification Message Corresponding WindowsConstant Message Description cn_CharToItem wm_CharToItem T ...