文件的下载分为NSURLConnection与NSURLSession两种,前一种有恨悠久的历史了。使用相对麻烦,后者是新出来的,增加了一些额外的功能。
一、NSURLConnection实现下载
TIPS:
1、
当
NSURLConnection
下载时
,
得到的
NSData
写入文件
时
,
data
并没有
占用多大内存
.
(
即使文件很大
)
2、
一点点在传
.
做的是磁盘缓存
.
而不是内存缓存机制。
3、了解在
NSURLConnection
上加代理。
[con
setDelegateQueue
:[[NSOperationQueue
alloc]
init]]
4、
NSURLResponse
记录的了
url, mineType, exceptedContentLength, suggestedFileName
等属性
.
下载时用得着
.
以下程序实现追踪下载百分比的下载(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
- {
-
- self.progress = progress;
-
-
- NSURLRequest *request = [NSURLRequest requestWithURL:url];
-
-
- NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
-
-
-
- [connection setDelegateQueue:[[NSOperationQueue alloc] init]];
-
-
- [connection start];
- }
-
- #pragma mark - 代理方法
-
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- {
- NSLog(@"%@ %lld", response.suggestedFilename, response.expectedContentLength);
-
- NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
- self.cachePath = [cachePath stringByAppendingPathComponent:response.suggestedFilename];
-
- self.fileLength = response.expectedContentLength;
-
- self.currentLength = 0;
-
-
- [self.dataM setData:nil];
- }
-
-
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- {
-
- [self.dataM appendData: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);
- }];
- }
- }
-
-
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection
- {
- NSLog(@"%s %@", __func__, [NSThread currentThread]);
-
-
- [self.dataM writeToFile:self.cachePath atomically:YES];
- }
-
-
- - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- {
- NSLog(@"%@", error.localizedDescription);
- }
-
- @end
二、NSURLSession实现下载
NSURLSession能实现断点续传,暂停下载等功能。
1、session提供的是
开了多个线程的异步下载.
2、下载的暂停与
续传: (session的
代理中的方法)
*弄一个NSData变量来保存下载东西.暂停时将下载任务task清空.
*
续传:将暂停时的data交给session继续下载,并将先前的data清空.
3、
task
一定要
resume
才开始执行
.
出处: http://blog.csdn.net/xn4545945