设为首页 加入收藏

TOP

iOS 学习 - 10下载(3) NSURLSession 音乐 篇
2017-10-13 10:24:19 】 浏览:2502
Tags:iOS 学习 下载 NSURLSession 音乐篇

使用 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
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Objective-c 动画 下一篇IOS CALayer(二)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目