URLSession 下載以及注意點需要解釋的全寫在註釋裏邊了看完代碼就什麼都明白了
用第三方框架 同時需要導入 libz.dylib依賴包
先來一個簡單的下載示例
#import "ViewController.h"
#import "SSZipArchive.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 1. url
NSString *urlString = @"http://192.168.32.2/歸檔.zip";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
// 2. session,蘋果爲了方便程序員的使用,提供過了一個全局的網絡會話單例
NSURLSession *session = [NSURLSession sharedSession];
// 3. 會話任務 -> 下載,所有的網絡會話的任務,都是由會話發起的
/**
對於下載任務,默認保存在tmp文件夾中,程序員不需要關心清理緩存的問題
如果需要對下載文件進行後續處理,需要在回調方法中,自行處理
例如:下載一個小說的zip包,需要解壓縮,zip包就需要刪除
按照NSURLSession的回調,只需要解壓縮即可。
*/
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 下載完成之後的處理
NSLog(@"%@", location.path);
// 將文件解壓縮到緩存目錄
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 解壓縮
[SSZipArchive unzipFileAtPath:location.path toDestination:cacheDir];
}];
// 4. 繼續任務,所有的任務默認都是掛起的,需要程序員自己繼續
[task resume];
}
@end
然後是相應的注意點 以及一個 斷點下載的小例子
注意點
> 1. 在下載完成之後需要對URLSession 做finishTasksAndInvalidate操作;
> 或者進行invalidateAndCancel 操作也行
> 2. 下載的文件保存再temp問價夾中下載完成後會自動刪除,需要再下載完成的時候自行進行處理
> 3. 一旦對session發送了invalidateAndCancel消息,session就再也無法發起任務了!
> 4. 在處理臨時文件的時候調用[[NSFileManager defaultManager] copyItemAtPath:tempPath toPath:cachePath error:NULL]; 可以解決內存飆升問題
>5.
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate >
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
/**
重要
session對象,會對代理進行強引用,如果不調用invalidateAndCancel取消 session,會出現內存泄漏
官方文檔中的說名
The session object keeps a strong reference to the delegate until your app explicitly invalidates the session. If you do not invalidate the session by calling the invalidateAndCancel or resetWithCompletionHandler: method, your app leaks memory.
*/
- (NSURLSession *)session {
if (_session == nil) {
// session 是爲了方便程序員使用的全局的單例,如果要通過代理跟進下載進度,需要自己實例化一個session
// NSURLSession *session = [NSURLSession sharedSession];
// config可以配置session,指定session中的超時時長,緩存策略,安全憑據,cookie...
// 可以保證全局共享,統一在一個網絡會話中使用!
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
/**
隊列:如果指定nil,會默認使用異步執行隊列的代理方法
因爲:所有網絡操作默認都是異步的,因此不指定隊列,就是異步的
*/
// NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
}
return _session;
}
- (void)dealloc {
[self.session invalidateAndCancel];
NSLog(@"我去了");
}
/**
跟蹤下載進度
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// url
NSString *urlString = @"http://127.0.0.1/01.C語言-語法預覽.mp4";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
// 數據任務
// 如果要跟蹤下載進度,在session中,同樣是需要代理
[[self.session downloadTaskWithURL:url] resume];
}
#pragma mark - 下載的代理方法
/** 下載完成 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
NSLog(@"+++%@", location);
/***********************************************/
// 完成任務 完成的時候需要進行釋放否則會造成內存泄露
[self.session finishTasksAndInvalidate];
}
// 以下兩個方法,在iOS7中,是必須的
// ios8中變成了可選的
/**
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;
NSLog(@"%f %@", progress, [NSThread currentThread]);
}
// 斷點續傳的
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
// 通常不用寫任何東西
}
@end