Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 252
Ron Avatar asked Oct 23 '17 07:10

Ron


People also ask

Can I delete photos from library if they are in an Album?

No, that is not possible. The standard albums are not storing photos. They are only referencing them in the library. If you delete a photo from the library , it will be removed from all albums that are using the photo.

How do I delete photos from photos on Mac?

Delete photos and videos In the Photos app on your Mac, select the items you want to delete. Do one of the following: Delete selected photos and videos in Days view: Press Delete, then click Delete. The selected items are deleted from your library and placed in the Recently Deleted album.

How do I delete photos from cluster?

Also, the creator of a group album can delete any photo added to that particular group album. To do this go to the photo you want removed and click the three dot icon at the foot of the photo (directly to the right of the comment text box). Click "Delete Photo".


2 Answers

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

like image 163
Warren Burton Avatar answered Oct 23 '22 21:10

Warren Burton


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)
})
like image 5
iwasrobbed Avatar answered Oct 23 '22 20:10

iwasrobbed