iphoneobjective-cuiimagepickercontrollerphotolibrary

Delete a photo from the user's photo library?


Is there a way I can delete an image that is loaded into my app from a UIImagePickerController?

I want to be able to delete the image from the user's photo library when the user performs a specific action.

I am prompting the user to choose a image from their library, then it gets loaded into my app at which point the app does some shnazzy animation, then actually deletes the image.

Please help!


Solution

  • Yes we can delete a photo. We can use PHAssetChangeRequest for this operation.

    From Apple:

    A request to create, delete, change metadata for, or edit the content of a Photos asset, for use in a photo library change block.

    class func deleteAssets(_ assets: NSFastEnumeration)
    

    where assets: An array of PHAsset objects to be deleted.

    PHAssetChangeRequest.deleteAssets([assetToDelete])
    

    So, you could use the above code to delete assets.

    below is swift 3 code,

    PHPhotoLibrary.shared().performChanges({
                let imageAssetToDelete = PHAsset.fetchAssets(withALAssetURLs: imageUrls as! [URL], options: nil)
                PHAssetChangeRequest.deleteAssets(imageAssetToDelete)
            }, completionHandler: {success, error in
                print(success ? "Success" : error )
            })