原理:
相册存完之后,可以得到文件唯一名称。
PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
localIdentifier = req.placeholderForCreatedAsset.localIdentifier;//存储,并拿到返回的随机文件名称
根据这个名称,可以读取相册中的图片
phAsset = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil].firstObject;//尝试去相册拿图片
if (phAsset != nil) {
//读取图片成功
}
所以封装一下存入相册的函数:
//保存图片到相册 mark 即唯一文件名
+(void)saveImagePhoto:(UIImage *)image mark:(NSString *)mark{
// 1.权限验证
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusDenied) {
TNSLog(@"请到【设置-隐私-照片】打开访问开关");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[WJAlertUtils alertMsg:@"请到【设置-隐私-照片】打开访问开关" vc:nil];
});
return;
} else if (status == PHAuthorizationStatusRestricted) {
TNSLog(@"没有相册权限");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[WJAlertUtils alertMsg:@"没有相册权限" vc:nil];
});
return;
}
//2.检查是否存过
TNSLog(@"检查是否存过");
NSString *localIdentifier = [[NSUserDefaults standardUserDefaults] objectForKey:mark];
if (localIdentifier == nil) {//没存过,肯定要存一下
[WJCommonUtils doSavePhotoAction:image withMark:mark];
}else{
PHAsset * asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil].firstObject;
if (asset == nil) {//拿不到图片资源,可能被删除了,重新存一下
[WJCommonUtils doSavePhotoAction:image withMark:mark];
}else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[WJAlertUtils alertMsg:@"该图片已存在" vc:nil];
});
TNSLog(@"已经存在该资源");
}
}
}
存图片的函数
+(void)doSavePhotoAction:(UIImage *)image withMark:(NSString *)mark{
NSError *err = nil;
__block PHAsset *phAsset = nil;
__block NSString *localIdentifier = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
//写入图片到相册
PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
localIdentifier = req.placeholderForCreatedAsset.localIdentifier;//存储,并拿到返回的随机文件名称
} error:&err];
if (err) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
TNSLog(@"保存照片出错:%@",err.localizedDescription);
[WJAlertUtils alertMsg:@"保存失败" vc:nil];
});
}else {
phAsset = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil].firstObject;//尝试去相册拿图片
if (phAsset != nil) {//成功拿到图片,说明存成功了,NSUserDefaults记录一下文件名
[[NSUserDefaults standardUserDefaults] setObject:phAsset.localIdentifier forKey:mark];
[[NSUserDefaults standardUserDefaults] synchronize];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[WJAlertUtils alertMsg:@"保存成功" vc:nil];
});
}
}
}