First you need to check if there is an album with a selection request, and then either add the image to the album, or create an album and then add the image.
#import <Photos/Photos.h> - (void)addImageToCameraRoll:(UIImage *)image { NSString *albumName = @"MyAlbum"; void (^saveBlock)(PHAssetCollection *assetCollection) = ^void(PHAssetCollection *assetCollection) { [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image]; PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection]; [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]]; } completionHandler:^(BOOL success, NSError *error) { if (!success) { NSLog(@"Error creating asset: %@", error); } }]; }; PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init]; fetchOptions.predicate = [NSPredicate predicateWithFormat:@"localizedTitle = %@", albumName]; PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:fetchOptions]; if (fetchResult.count > 0) { saveBlock(fetchResult.firstObject); } else { __block PHObjectPlaceholder *albumPlaceholder; [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ PHAssetCollectionChangeRequest *changeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName]; albumPlaceholder = changeRequest.placeholderForCreatedAssetCollection; } completionHandler:^(BOOL success, NSError *error) { if (success) { PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[albumPlaceholder.localIdentifier] options:nil]; if (fetchResult.count > 0) { saveBlock(fetchResult.firstObject); } } else { NSLog(@"Error creating album: %@", error); } }]; } }
source share