URLSession 下载以及注意点

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


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AVAudioPlayer 本身并不支持下载功能,如果需要监听下载进度,可以使用 NSURLSession 来进行下载,并通过 AVAudioPlayer 播放下载好的音频文件。 具体来说,可以在 NSURLSessionDelegate 协议中实现以下方法: ``` - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ // 将下载好的文件剪切到指定目录 NSString *destinationPath = [self getDestinationPathForDownloadedFile]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; if ([fileManager fileExistsAtPath:destinationPath]) { [fileManager removeItemAtPath:destinationPath error:nil]; } BOOL success = [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:destinationPath] error:&error]; if (success) { // 下载完成,发送通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"AVAudioPlayerDownloadProgressNotification" object:nil userInfo:@{@"progress":@(1.0)}]; } } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ float progress = (float)totalBytesWritten / totalBytesExpectedToWrite; // 发送下载进度通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"AVAudioPlayerDownloadProgressNotification" object:nil userInfo:@{@"progress":@(progress)}]; } ``` 在上面的代码中,我们实现了 NSURLSessionDelegate 协议中的两个方法。在 didFinishDownloadingToURL 方法中,我们将下载好的文件从临时目录剪切到指定目录,并发送下载进度为 1.0 的通知。在 didWriteData 方法中,我们计算出当前的下载进度,并将其作为 userInfo 传递给通知中心。 在 AVAudioPlayer 播放音频文件之前,可以先判断文件是否已经下载完成,如果下载完成,则直接使用 AVAudioPlayer 播放文件,如果未完成,则等待下载完成之后再进行播放。在接收到下载进度通知之后,可以更新 UI 上的下载进度条。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值