Coding Notes iOS/Objective-C

Delete Duplicate Photo Albums in XCode Objective-C

I accidentally created too many photo albums with the same name, I needed a solution to delete it all without manually deleting it. There’s probably an easier way to do this if you know it let me know.

NSString *albumName = @"SOME ALBUM";
__block PHAssetCollection *albumCollection = [[PHAssetCollection alloc] init];
PHFetchOptions *albumOptions = [[PHFetchOptions alloc] init];
[albumOptions setPredicate:[NSPredicate predicateWithFormat:@"estimatedAssetCount >= 0"]];

PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:albumOptions];

dispatch_async(dispatch_get_main_queue(), ^{
    [userAlbums enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[PHAssetCollection class]]) {
            PHAssetCollection *objAsset = (PHAssetCollection *)obj;
            if ([objAsset.localizedTitle isEqualToString:self->_albumName]) {
                NSLog(@"FOUND: %@", objAsset.localizedTitle);
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    [PHAssetCollectionChangeRequest deleteAssetCollections:@[objAsset]];
                } completionHandler:^(BOOL success, NSError * _Nullable error) {
                    if (success) {
                        NSLog(@"Deleted");
                    } else {
                        NSLog(@"Not Deleted");
                    }
                }];
            }
        }
    }];

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.