ios 下载文件

/**

*  下载文件

*

*  @param path    url路径

*  @param success  下载成功

*  @param failure  下载失败

*  @param progress 下载进度

*/

+ (void)downloadWithPath:(NSString *)path

success:(HttpSuccessBlock)success

failure:(HttpFailureBlock)failure

progress:(HttpDownloadProgressBlock)progress;


+ (void)downloadWithPath:(NSString *)path

success:(HttpSuccessBlock)success

failure:(HttpFailureBlock)failure

progress:(HttpDownloadProgressBlock)progress {

//获取完整的url路径

NSString * urlString = [kBaseUrl stringByAppendingPathComponent:path];

//下载

NSURL *URL = [NSURL URLWithString:urlString];

NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [[AFHttpClient sharedClient] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

progress(downloadProgress.fractionCompleted);

} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

//获取沙盒cache路径

NSURL * documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];

return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];

} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

if (error) {

failure(error);

} else {

success(filePath.path);

}

}];

[downloadTask resume];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容