Search code examples
iosswiftimagephoto-gallery

Delete image from Photo Gallery


In my app I have a function that saves images into custom collection album created in Photo Gallery:

func save(image: UIImage) {
    if assetCollection == nil {
        return
    }
    PHPhotoLibrary.shared().performChanges({
        let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
        let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
        let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
        let enumeration: NSArray = [assetPlaceHolder!]
        albumChangeRequest!.addAssets(enumeration)
    }, completionHandler: nil)
}

UIImages are created by user in previous VC. Also, they are saved into documents directory and then displayed in my app in collection view on a separate VC.

Later on user can select desired photo, which is then displayed in new VC and delete it by clicking on Trash TabBarButton. When the button is pressed image gets removed from Documents Directory and so it disappears from collection view as well.

What I'm trying to achieve is to delete this photo from Photo Gallery simultaneously. So, when user click on Trash button, delete selected photo from Documents Directory and Photo Gallery as well.

What I achieved so far - created functions that take image's URLs, and removes item according to that url, as I did with Documents Directory:

func deleteSelectedPhotoFromGallery() {
    PHPhotoLibrary.shared().performChanges({
        let imageAssetToDelete = PHAsset.fetchAssets(withALAssetURLs: self.loadURL() as! [URL], options: nil)
        PHAssetChangeRequest.deleteAssets(imageAssetToDelete)
    })
}

EDIT: Thats how I get URLs:

func loadURL() -> [NSURL?]? {
    let retrievedData = UserDefaults.standard.object(forKey: DefaultKeys.imagesURL.rawValue) as? [String]
    return retrievedData?.map { NSURL(string: $0) }
}

Problems:

  • fetchAssets(withALAssetURLs) - will be deprecated, what to use instead?
  • how to get image URL that is being saved to PhotoLibrary?

Basically, I need some method that will delete image from Photo Gallery that is being saved before. I wonder if you could somehow detect image URL or path when it was saved, then store it's path into UserDefaults and after that delete it using it's path or URL.

There have been questions regarding this issue before, but they used ImagePicker to detect image URL and where written in objc, but I would like to have a solution in swift and without using ImagePicker.

Thanks.


Solution

  • fetchAssets(withALAssetURLs) - will be deprecated, what to use instead? how to get image URL that is being saved to PhotoLibrary?

    You don’t. That is why it is deprecated! You get the asset’s localIdentifier. This allows you to access the asset and delete it later.

    Your completion handler is empty. That’s the problem. Write the completion handler and get the local identifier from the placeholder.