iOS保存图片到自定义的相册
保存图片到自定义的相册
+ (void)saveImageToAsset:(UIImage*)image {
NSString*collectionTitle =BLDisplayName;
__blockPHAssetCollection*collection =nil;
PHFetchResult<PHAssetCollection*> *results = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for(PHAssetCollection*getCollectioninresults) {
if([getCollection.localizedTitleisEqualToString:collectionTitle]) {
collection = getCollection;
}
}
__blockNSString*assetIdentifier =nil;
__blockNSString*collectionIdentifier =nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 1.将图片保存到相簿
assetIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
}completionHandler:^(BOOLsuccess,NSError*_Nullableerror) {
if(success) {
// 2.创建自定义的相薄
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
if(!collection) {
collectionIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionTitle].placeholderForCreatedAssetCollection.localIdentifier;
}
}completionHandler:^(BOOLsuccess,NSError*_Nullableerror) {
if(success) {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 3. 将相片保存到自定义的相薄
if(!collection) {
collection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionIdentifier] options:nil].lastObject;
}
PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetIdentifier] options:nil].lastObject;
PHAssetCollectionChangeRequest *requestCollection = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
// 添加进自定义的相册
[requestCollectionaddAssets:@[asset]];
}completionHandler:^(BOOLsuccess,NSError*_Nullableerror) {
NSLog(@"%@",success?@"保存成功":@"保存失败");
}];
}else{
NSLog(@"%@",@"保存失败");
}
}];
}else{
NSLog(@"%@",@"保存失败");
}
}];
}