文件下載
//創(chuàng)建傳話管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cn.bing.com/az/hprichbg/rb/WindmillLighthouse_ZH-CN12870536851_1920x1080.jpg"]];
//下載文件
/*
第一個參數(shù):請求對象
第二個參數(shù):progress 進(jìn)度回調(diào)
第三個參數(shù):destination 回調(diào)(目標(biāo)位置)
有返回值
targetPath:臨時文件路徑
response:響應(yīng)頭信息
第四個參數(shù):completionHandler 下載完成后的回調(diào)
filePath:最終的文件路徑
*/
NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request
progress:^(NSProgress * _Nonnull downloadProgress) {
//下載進(jìn)度
NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
}
destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//保存的文件路徑
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
return [NSURL fileURLWithPath:fullPath];
}
completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"%@",filePath);
}];
//執(zhí)行Task
[download resume];
文件上傳
//創(chuàng)建會話管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//發(fā)送post請求上傳路徑
/*
第一個參數(shù):請求路徑
第二個參數(shù):字典(非文件參數(shù))
第三個參數(shù):constructingBodyWithBlock 處理要上傳的文件數(shù)據(jù)
第四個參數(shù):進(jìn)度回調(diào)
第五個參數(shù):成功回調(diào) responseObject響應(yīng)體信息
第六個參數(shù):失敗回調(diào)
*/
[manager POST:@"服務(wù)器ip" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
UIImage *image = [UIImage imageNamed:@"xxx.png"];
NSData *imageData = UIImagePNGRepresentation(image);
//使用formData拼接數(shù)據(jù)
/* 方法一:
第一個參數(shù):二進(jìn)制數(shù)據(jù) 要上傳的文件參數(shù)
第二個參數(shù):服務(wù)器規(guī)定的
第三個參數(shù):文件上傳到服務(wù)器以什么名稱保存
*/
[formData appendPartWithFileData:imageData name:@"file" fileName:@"xxx.png" mimeType:@"image/png"];
//方法二:
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@""] name:@"file" fileName:@"xxx.png" mimeType:@"image/png" error:nil];
//方法三:
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@""] name:@"file" error:nil];
}
progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"上傳成功.%@",responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上傳失敗.%@",error);
}];
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者