通过AFHTTPSessionManger去下载管理
分别是:下载到本地和存入到CoreData中
#define kCachesPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] // 沙盒路径
下载
- (void)actionDownload:(UIButton *)button
{
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"下载" message:@"请选择版本" preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *alertActionCancle = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
button.userInteractionEnabled = YES;
return;
}];
[alertVC addAction:alertActionCancle];
UIAlertAction *alertActionOne = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"普通(%.2fM)", [self.model.mp3size_32 floatValue] / 1024 / 1024] style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
[self downLoadMonitorWithUrl:self.model.playUrl32]; // 下载
// 调用进度条
[self showProgressView];
}];
[alertVC addAction:alertActionOne];
UIAlertAction *alertActionTwo = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"清晰(%.2fM)", [self.model.mp3size_64 floatValue] / 1024 / 1024] style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
[self downLoadMonitorWithUrl:self.model.playUrl64]; // 下载
[self showProgressView];
}];
[alertVC addAction:alertActionTwo];
[self presentViewController:alertVC animated:YES completion:nil];
if ([self isExistFile] == NO) {
[self createFile];
}
button.userInteractionEnabled = NO;
}
进度条
// 进度条
- (void)showProgressView
{
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:(UIProgressViewStyleBar)];
self.progressView.frame = CGRectMake(kScreenWidth / 5 + 30, self.playerView.bottomImage.height / 3.5 + 10, kScreenWidth - 2 * (kScreenWidth / 5 + 30), 30);
[self.playerView.bottomImage addSubview:self.progressView];
self.progressView.trackTintColor = [UIColor grayColor];
self.progressView.progressTintColor = [UIColor blueColor];
}
- (void)downLoadMonitorWithUrl:(NSString *)url
{
// 1.创建网络管理者
// AFHTTPSessionManager 基于NSURLSession
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 2.利用网络管理者下载数据
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSProgress *progress = nil;
NSString *oldPath = [NSString stringWithFormat:@"%@/Download", kCachesPath];
NSString *path = [oldPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3", self.model.title]];
NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
// NSLog(@"---%@", path);
// 返回下载后拼接路径
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
// 下载成功后提示
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
// [self performSelector:@selector(dimissAlert:) withObject:alert afterDelay:1.0];
// 打开交互
self.playerView.downloadBtn.userInteractionEnabled = YES;
[self.progressView removeFromSuperview];
// 成功后 添加到coredata中
[self addEntityMusicUrl:[NSString stringWithFormat:@"%@/%@.mp3", oldPath, self.model.title] imageUrl:self.model.coverLarge totalTime:self.model.Duration];
}];
/*
要跟踪进度,需要使用 NSProgress,是在 iOS 7.0 推出的,专门用来跟踪进度的类!
NSProgress只是一个对象!如何跟踪进度!-> KVO 对属性变化的监听!
@property int64_t totalUnitCount; 总单位数
@property int64_t completedUnitCount; 完成单位数
*/
// 给Progress添加监听 KVO
[progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
// 3.启动任务
[downTask resume];
}
监听progress 进度,只要progress一发生改变就会触发方法
// 收到通知调用的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(NSProgress *)object
change:(NSDictionary *)change context:(void *)context
{
// 回到主队列刷新UI
dispatch_async(dispatch_get_main_queue(), ^{
[self.progressView setProgress:1.0 * object.completedUnitCount / object.totalUnitCount animated:YES];
});
}
判断文件夹是否存在
// 判断一个文件夹是否存在(经常使用)
- (BOOL)isExistFile
{
NSString *oldPath = [NSString stringWithFormat:@"%@/Download", kCachesPath];
return [[NSFileManager defaultManager] isExecutableFileAtPath:oldPath];
}
创建文件夹
- (void)createFile
{
NSString *path = [NSString stringWithFormat:@"%@/Download", kCachesPath];
// withIntermediateDirectories 如果填YES,如果创建的文件已经存在,可以将其覆盖,反之文件创建失败
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
利用CoreDate存储数据
- (void)addEntityMusicUrl:(NSString *)url imageUrl:(NSString *)imageUrl totalTime:(NSNumber *) totalTime
{
NSEntityDescription *musicED = [NSEntityDescription entityForName:@"DownloadMusic" inManagedObjectContext:self.managerContext];
// 根据实体描述创建实体对象
DownloadMusic *myMusic = [[DownloadMusic alloc] initWithEntity:musicED insertIntoManagedObjectContext:self.managerContext];
myMusic.url = url;
// NSLog(@"_+_+_+%@", myMusic.url);
myMusic.imageUrl = imageUrl;
myMusic.totalTime = totalTime;
myMusic.name = self.model.title;
// 同步数据
[self.managerContext save:nil];
}