AFNetWorking下载网络音乐视频或者图片

时间:2022-05-07 07:10:11

healp.h

#import <Foundation/Foundation.h>

@interface Healp : NSObject

typedef void(^filePath)(NSString *data);

+(void)downLoadUrlString:(NSString *)urlStr returnStr:(filePath)str;

@end

healp.m

#import "Healp.h"
#import <AFNetworking.h>

@implementation Healp

+(void)downLoadUrlString:(NSString *)urlStr returnStr:(filePath)str{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
NSURLSessionDownloadTask *download =[manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:response.suggestedFilename];
return [NSURL fileURLWithPath:filePath];

} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSString *strp = [NSString stringWithFormat:@"%@",filePath];
str(strp);
}];
[download resume];

}
@end

调用

#import "ViewController.h"
#import "Healp.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.simple = [TonePlayerSimple tonePlayer];

NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *urlStr = [NSString stringWithFormat:@"http://fdfs.xmcdn.com/group11/M00/AD/5F/wKgDa1ZfFi-gRNYMABuxsyS4ea4688.mp3"];
NSString *str = [urlStr lastPathComponent];//截取文件名wKgDa1ZfFi-gRNYMABuxsyS4ea4688.mp3
NSString *filePath = [NSString stringWithFormat:@"%@/%@",docDirPath,str];
BOOL isHave = [[NSFileManager defaultManager] fileExistsAtPath:filePath];//判断是不是已经存在
if (isHave) {
//如果已经下载就直接使用
//直接调用filePath
}else{
//如果没有下载就先下载在使用
[Healp downLoadUrlString:urlStr returnStr:^(NSString *data) {
//直接调用data
}];

}
}

想要了解更多请关注公众号
AFNetWorking下载网络音乐视频或者图片