項(xiàng)目中需要實(shí)現(xiàn)一個(gè)下載器信柿,用來下載項(xiàng)目中的圖片和視頻到本地相冊中冀偶。
思路:
1.使用AFNetworking的NSURLSessionDownloadTask作為下載的API。
2.使用系統(tǒng)的PHAssetCreationRequest角塑,把下載的圖片或者視頻保存到相冊蔫磨。
AFNetworking部分就很明了了,創(chuàng)建一個(gè)SessionConfiguration,
創(chuàng)建一個(gè)AFURLSessionManager的manager圃伶。
然后用這個(gè)manager創(chuàng)建一個(gè)下載請求堤如。
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
NSURL* url = [NSURL URLWithString:urlStr];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask* task = [manager downloadTaskWithRequest:(NSURLRequest *)request
progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler];
出現(xiàn)坑的地方在于webp格式的圖片不能正常保存到相冊里。解決辦法是引用第三方庫YYImage窒朋,實(shí)現(xiàn)webp格式的正常解碼搀罢。就ok了。這是下載成功回調(diào):
completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error){
if (error) {
//下載失敗;
}else{
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) { //確認(rèn)有權(quán)限
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
if (isVideo) {
PHAssetCreationRequest* request = [PHAssetCreationRequest creationRequestForAsset];
PHAssetResourceCreationOptions* option = PHAssetResourceCreationOptions.new;
option.shouldMoveFile = YES;
[request addResourceWithType:PHAssetResourceTypeVideo fileURL:filePath options:option];
}else{
//先以NSData形式讀出
NSData* data = [NSData dataWithContentsOfURL:filePath];
//用YYImage解析data侥猩,YYImage兼容了webp格式榔至。
YYImage* yyimage = [YYImage imageWithData:data];
//保存到相冊
[PHAssetCreationRequest creationRequestForAssetFromImage:yyimage];
}
} completionHandler:^(BOOL success, NSError *_Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
//保存失敗;
}else{
//保存成功;
}
});
}];
}else{ //沒有相冊權(quán)限
//保存失敗,沒有相冊權(quán)限
}
}];
}
}