项目中需要实现一个下载器,用来下载项目中的图片和视频到本地相册中。
思路:
1.使用AFNetworking的NSURLSessionDownloadTask作为下载的API。
2.使用系统的PHAssetCreationRequest,把下载的图片或者视频保存到相册。
AFNetworking部分就很明了了,创建一个SessionConfiguration,
创建一个AFURLSessionManager的manager。
然后用这个manager创建一个下载请求。
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];
出现坑的地方在于webp格式的图片不能正常保存到相册里。解决办法是引用第三方库YYImage,实现webp格式的正常解码。就ok了。这是下载成功回调:
completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error){
if (error) {
//下载失败;
}else{
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) { //确认有权限
[[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{ //没有相册权限
//保存失败,没有相册权限
}
}];
}
}