iosswiftphotophassetphphotolibrary

Deleting photo from Photo Library using Photo framework


I am writing a photo album app which can access the photo from the user's photo library, add filter, and delete photo. I used the Photo framework to delete an asset with PHAssetChangeRequest.deleteAssets(assetToDelete). The class of asset here is PHAsset.

// Delete the photo from library    
@IBAction func deleteBtnPressed(_ sender: Any) {
        let assetToDelete = self.asset
        if let assetToDelete = assetToDelete
          {
            PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.deleteAssets(assetToDelete)
          })
        }
      }

But error happen here, "Argument type 'PHAsset' does not conform to expected type 'NSFastEnumeration'".

So I change the type of assetToDelete as Xcode recommended:

PHAssetChangeRequest.deleteAssets(assetToDelete as! NSFastEnumeration)

It still doesn't work, the error is shows that:

Could not cast value of type 'PHAsset' to 'NSFastEnumeration'

Does anyone know how to deal with this? Thanks!


Solution

  • The clue is in the name ‘assets’ plural - the API wants an array or any other collection type that conforms to NSFastEnumeration e.g Set

    PHAssetChangeRequest.deleteAssets([assetToDelete] as NSArray)

    https://developer.apple.com/documentation/photos/phassetchangerequest/1624062-deleteassets