0

I'm using PhotoKit and I've created an album

PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: RooPhotoAlbum.albumName)

But I found some issue with first time saving file to the album So I need to delete it so I could reproduce this issue. How to delete an Album programmatically on iOS?

Cœur
  • 37,241
  • 25
  • 195
  • 267
tianyu
  • 44
  • 4

3 Answers3

2

Here's a function to delete a custom album programmatically with error handling:

func deleteAlbum(albumName: String) {
    let options = PHFetchOptions()
    options.predicate = NSPredicate(format: "title = %@", albumName)
    let album = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: options)

    // check if album is available
    if album.firstObject != nil {

        // request to delete album
    PHPhotoLibrary.shared().performChanges({
        PHAssetCollectionChangeRequest.deleteAssetCollections(album)
    }, completionHandler: { (success, error) in
        if success {
            print(" \(albumName) removed succesfully")
        } else if error != nil {
            print("request failed. please try again")
        }
    })
    } else {
        print("requested album \(albumName) not found in photos")
    }
}

How to use -

deleteAlbum(albumName: "YourAlbumName")
Cœur
  • 37,241
  • 25
  • 195
  • 267
0
let options = PHFetchOptions()
options.predicate = NSPredicate(format: "title = %@", RootPhotoAlbum.albumName)
let album = PHCollectionList.fetchCollectionLists(with: .folder, subtype: .any, options: options)

PHPhotoLibrary.shared().performChanges({
    PHAssetCollectionChangeRequest.deleteAssetCollections([album] as NSArray)
}, completionHandler: { (success, error) in
    if success {
        // Deleted successfully
    } else if let error = error {
        // Error deleting album
    }
})
Douglas Silva
  • 145
  • 1
  • 9
0

Douglas' answer fetches PHCollectionList then tries to perform an action on PHAssetCollection which fails. You should do this:

options.predicate = NSPredicate(format: "title = %@", "AlbumName")
let album = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: options)

PHPhotoLibrary.shared().performChanges({
    PHAssetCollectionChangeRequest.deleteAssetCollections(album)
}, completionHandler: { (success, error) in
    if success {
        //success
    } else if let error = error {
        //failed
    }
})
Maysam
  • 7,246
  • 13
  • 68
  • 106