7

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!

Ron
  • 110
  • 1
  • 9

2 Answers2

11

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

Warren Burton
  • 17,451
  • 3
  • 53
  • 73
5

The more correct way would be to fetch from the library first:

let assetIdentifiers = assetsToDeleteFromDevice.map({ $0.localIdentifier })
let assets = PHAsset.fetchAssets(withLocalIdentifiers: assetIdentifiers, options: nil)
PHPhotoLibrary.shared().performChanges({
    PHAssetChangeRequest.deleteAssets(assets)
})
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195