而後是相應的注意點 以及一個 斷點下載的小例子ios
- 注意點
- > 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
-
- - (NSURLSession *)session {
- if (_session == nil) {
-
-
-
-
- NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
-
-
-
- _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
- }
- return _session;
- }
-
- - (void)dealloc {
- [self.session invalidateAndCancel];
-
- NSLog(@"我去了");
- }
-
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
-
-
- NSString *urlString = @"http://127.0.0.1/01.C語言-語法預覽.mp4";
- urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- NSURL *url = [NSURL URLWithString:urlString];
-
-
-
- [[self.session downloadTaskWithURL:url] resume];
-
- }
-
- #pragma mark - 下載的代理方法
- - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
- didFinishDownloadingToURL:(NSURL *)location {
- NSLog(@"+++%@", location);
-
-
- [self.session finishTasksAndInvalidate];
- }
-
- - (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