iOS 学习

使用 NSURLSession 下载,需要注意的是文件下载文件之后会自动保存到一个临时目录,需要开发人员自己将此文件重新放到其他指定的目录中

//
//  ViewController.m
//  Web相关
//
//  Copyright © 2016年 asamu. All rights reserved.
//
//http://mr7.doubanio.com/832d52e9c3df5c13afd7243a770c094f/0/fm/song/p294_128k.mp3
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
@property(nonatomic,strong)AVAudioPlayer *avaudioPlayer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self downloadFile];
}

-(void)playMusic{
    //获取缓存目录
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //获取缓存目录下的歌曲
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"xxx.mp3"];
    /*
     fileURLWithPath:  文件链接
     URLWithString:    http链接
     */
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
    //判断文件存不存在
    if(
       [[NSFileManager defaultManager]fileExistsAtPath:filePath]){
        NSLog(@"exist");
    
    
        NSError *error;
        _avaudioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:&error];
        
        if (error) {
        NSLog(@"%@",error.localizedDescription);
        }
    //加入缓存
    [_avaudioPlayer prepareToPlay];
    //播放
    [_avaudioPlayer play];
    }
}
#pragma mark - 私有方法
-(void)downloadFile{
    
    NSString *filename = @"xxx.mp3";
    //获取 URL
    NSString *urlStr = [NSString stringWithFormat:@"http://mr7.doubanio.com/832d52e9c3df5c13afd7243a770c094f/0/fm/song/p294_128k.mp3",filename];
    NSURL *url = [NSURL URLWithString:urlStr];
    //创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //创建会话(全局会话)
    NSURLSession *session = [NSURLSession sharedSession];
    //创建任务
    NSURLSessionDownloadTask *downloadTak = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //获取缓存目录
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        //歌存到缓存目录,并命名
        NSString *savePath = [cachePath stringByAppendingPathComponent:filename];
        //得到路径,打开终端 open 去掉 xxx.mp3 的目录,就可以直观的看到 MP3文件的下载
        NSLog(@"%@",savePath);
        
        NSURL *saveurl = [NSURL fileURLWithPath:savePath];
        /*
         1.location 是下载后的临时保存路径,需要将它移动到需要保存的位置
         2.move faster than copy
           (1).因为 copy 需要在磁盘上生成一个新的文件,这个速度是很慢的;
           (2).copy 后,还要把临时文件删除,move 这一步就行了 = (copy + remove)
         3.move 有两个功能 一是移动  二是重命名
         */
        NSError *saveError;
        [[NSFileManager defaultManager]moveItemAtURL:location toURL:saveurl error:&saveError];
        
        //如果错误存在,输出
        if (saveError) {
            NSLog(@"%@",saveError.localizedDescription);
        }
        //播放
        [self playMusic];
    }];
    //执行任务
    [downloadTak resume];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
原文地址:https://www.cnblogs.com/asamu/p/5426926.html