iOS开发之断点下载时session造成的内存泄漏

然后是相应的注意点 以及一个 断点下载的小例子

 

 

[objc] view plain copy
  1. 注意点   
  2.  > 1. 在下载完成之后需要对URLSession 做finishTasksAndInvalidate操作;   
  3.  >    或者进行invalidateAndCancel 操作也行  
  4.  > 2. 下载的文件保存再temp问价夹中下载完成后会自动删除,需要再下载完成的时候自行进行处理  
  5.  > 3.  一旦对session发送了invalidateAndCancel消息,session就再也无法发起任务了!  
  6.   > 4. 在处理临时文件的时候调用[[NSFileManager defaultManager] copyItemAtPath:tempPath   toPath:cachePath error:NULL]; 可以解决内存飙升问题  
  7.  >5.  
  8.   
  9. #import "ViewController.h"  
  10.   
  11. @interface ViewController () <NSURLSessionDownloadDelegate >  
  12. @property (nonatomic, strong) NSURLSession *session;  
  13. @end  
  14.   
  15. @implementation ViewController  
  16. /** 
  17.  重要 
  18.  session对象,会对代理进行强引用,如果不调用invalidateAndCancel取消    session,会出现内存泄漏 
  19.   官方文档中的说名 
  20.  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. 
  21.  */  
  22.   
  23. - (NSURLSession *)session {  
  24.     if (_session == nil) {  
  25.         // session 是为了方便程序员使用的全局的单例,如果要通过代理跟进下载进度,需要自己实例化一个session  
  26.         //    NSURLSession *session = [NSURLSession sharedSession];  
  27.         // config可以配置session,指定session中的超时时长,缓存策略,安全凭据,cookie...  
  28.         // 可以保证全局共享,统一在一个网络会话中使用!  
  29.         NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];  
  30.          
  31.         /** 
  32.          队列:如果指定nil,会默认使用异步执行队列的代理方法 
  33.          因为:所有网络操作默认都是异步的,因此不指定队列,就是异步的 
  34.          */  
  35.         //    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc] init]];  
  36.         _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];  
  37.     }  
  38.     return _session;  
  39. }  
  40.   
  41. - (void)dealloc {  
  42.     [self.session invalidateAndCancel];  
  43.      
  44.     NSLog(@"我去了");  
  45. }  
  46.   
  47. /** 
  48.  跟踪下载进度 
  49.  */  
  50. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  
  51.   
  52.     // url  
  53.     NSString *urlString = @"http://127.0.0.1/01.C语言-语法预览.mp4";  
  54.     urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
  55.     NSURL *url = [NSURL URLWithString:urlString];  
  56.      
  57.     // 数据任务  
  58.     // 如果要跟踪下载进度,在session中,同样是需要代理  
  59.     [[self.session downloadTaskWithURL:url] resume];  
  60.      
  61. }  
  62.   
  63. #pragma mark - 下载的代理方法  
  64. /** 下载完成 */  
  65. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  
  66. didFinishDownloadingToURL:(NSURL *)location {  
  67.     NSLog(@"+++%@", location);  
  68.     /***********************************************/  
  69.     // 完成任务 完成的时候需要进行释放否则会造成内存泄露  
  70.     [self.session finishTasksAndInvalidate];  
  71. }  
  72.   
  73. // 以下两个方法,在iOS7中,是必须的  
  74. // ios8中变成了可选的  
  75. /** 
  76.  bytesWritten                   本次下载字节数 
  77.  totalBytesWritten              已经下载字节数 
  78.  totalBytesExpectedToWrite      总下载字节数(文件大小) 
  79.  */  
  80. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  
  81.       didWriteData:(int64_t)bytesWritten  
  82.  totalBytesWritten:(int64_t)totalBytesWritten  
  83. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {  
  84.   
  85.     // 进度  
  86.     float progress = (float) totalBytesWritten / totalBytesExpectedToWrite;  
  87.     NSLog(@"%f %@", progress, [NSThread currentThread]);  
  88. }  
  89.   
  90. // 断点续传的  
  91. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  
  92.  didResumeAtOffset:(int64_t)fileOffset  
  93. expectedTotalBytes:(int64_t)expectedTotalBytes {  
  94.     // 通常不用写任何东西  
  95. }  
  96. @end  

posted on 2016-07-19 13:38  程序“猿”  阅读(3480)  评论(0编辑  收藏  举报

导航