// // MTVideoDownTool.m // Hellomacau // // Created by Simon on 2020/4/30. // Copyright © 2020 Simon. All rights reserved. // #import "MTVideoDownTool.h" @implementation MTVideoDownTool + (void)downloadAudioWithUrl:(NSString *)url saveDirectoryPath:(NSString *)directoryPath fileName:(NSString *)fileName finish:(FinishBlock )finishBlock failed:(Failed)failed { NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); directoryPath = [paths objectAtIndex:0]; NSString *mp3path = [NSString stringWithFormat:@"%@.mp3",fileName]; NSString *file_path = [directoryPath stringByAppendingPathComponent:mp3path]; NSFileManager *fm = [NSFileManager defaultManager]; /// 判断文件是否已经存在 if ([fm fileExistsAtPath:file_path]){ // finishBlock(file_path); failed(1); }else{ /// 不存在时 NSURL *URL = [NSURL URLWithString:url]; NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; //AFN3.0+基于封住URLSession的句柄 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; //请求 NSURLRequest *request = [NSURLRequest requestWithURL:URL]; //下载Task操作 NSURLSessionDownloadTask *_downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) { //进度 NSString *ss = [NSString stringWithFormat:@"已下载:%@",downloadProgress.localizedDescription]; ShowMessage(ss); } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename]; return [NSURL fileURLWithPath:path]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { // filePath就是你下载文件的位置,你可以解压,也可以直接拿来使用 NSString *armFilePath = [filePath path];// 将NSURL转成NSString //重命名 NSString *nNameFilePath = [MTVideoDownTool p_setupFileRename:armFilePath andFileName:fileName]; finishBlock(nNameFilePath); }]; [_downloadTask resume]; } } /** 对文件重命名 @param filePath 旧路径 @return 新路径 */ + (NSString *)p_setupFileRename:(NSString *)filePath andFileName:(NSString *)Name{ NSString *lastPathComponent = [NSString new]; //获取文件名: 视频.MP4 lastPathComponent = [filePath lastPathComponent]; //获取后缀:MP4 NSString *pathExtension = [filePath pathExtension]; //用传过来的路径创建新路径 首先去除文件名 NSString *pathNew = [filePath stringByReplacingOccurrencesOfString:lastPathComponent withString:@""]; //然后拼接新文件名: NSString *moveToPath = [NSString stringWithFormat:@"%@%@.%@",pathNew,Name,pathExtension]; NSFileManager *fileManager = [NSFileManager defaultManager]; //通过移动该文件对文件重命名 BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil]; if (isSuccess) { NSLog(@"rename success"); }else{ NSLog(@"rename fail"); } return moveToPath; } @end