1.創(chuàng)建下載模型TNDownloadModel
/**
* 下載文件
*
* @param downloadURL 下載鏈接
* @param success 請求結(jié)果
* @param faliure 錯誤信息
*/
+(void)downloadURL:(NSString *) downloadURL progress:(void (^)(NSProgress *downloadProgress))progress destination:(void (^)(NSURL *targetPath))destination failure:(void(^)(NSError *error))faliure{
//1.創(chuàng)建管理者
AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
//2.下載文件
/*
第一個參數(shù):請求對象
第二個參數(shù):下載進度
第三個參數(shù):block回調(diào)职抡,需要返回一個url地址,用來告訴AFN下載文件的目標(biāo)地址
targetPath:AFN內(nèi)部下載文件存儲的地址,tmp文件夾下
response:請求的響應(yīng)頭
返回值:文件應(yīng)該剪切到什么地方
第四個參數(shù):block回調(diào),當(dāng)文件下載完成之后調(diào)用
response:響應(yīng)頭
filePath:文件存儲在沙盒的地址 == 第三個參數(shù)中block的返回值
error:錯誤信息
*/
//2.1 創(chuàng)建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: downloadURL]];
NSURLSessionDownloadTask *downloadTask = [manage downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {//進度
if (downloadProgress) {
progress(downloadProgress);
}
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//拼接文件全路徑
NSString *fullpath = [caches stringByAppendingPathComponent:response.suggestedFilename];
NSURL *filePathUrl = [NSURL fileURLWithPath:fullpath];
return filePathUrl;
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nonnull filePath, NSError * _Nonnull error) {
if (error) {
faliure(error);
}
if(filePath){
destination(filePath);
}
}];
//3.啟動任務(wù)
[downloadTask resume];
}
2.下載事件響應(yīng)
-(void)upDownload{
@weakify(self);
[TNDownloadModel downloadElectronicProtocolContract:self.contract progress:^(NSProgress *downloadProgress) {
//下載進度
NSString *progress = [NSString stringWithFormat:@"下載:%f%%",100.0 * downloadProgress.completedUnitCount/downloadProgress.totalUnitCount];
} destination:^void(NSURL *targetPath) {//下載完畢
//targetPath下載完成的本地存儲路徑
//下載完成后的處理
} failure:^(NSError *error) {
//下載過程中遇到的錯誤
}];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者