0

I'm trying to get the last image from my photo library and delete it. There are answers on getting the last image and answers to delete an image using its URL, but I find it difficult to consolidate both


var images:[UIImage] = []
    func fetchPhotos () {
        // Sort the images by descending creation date and fetch the first
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)]
        fetchOptions.fetchLimit = 1

        // Fetch the image assets
        let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)


        if fetchResult.count > 0 {
            let totalImageCountNeeded = 1 // <-- The number of images to fetch
            fetchPhotoAtIndex(0, totalImageCountNeeded, fetchResult)
        }
    }

    func fetchPhotoAtIndex(_ index:Int, _ totalImageCountNeeded: Int, _ fetchResult: PHFetchResult<PHAsset>) {


        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = true

        // Perform the image request
        PHImageManager.default().requestImage(for: fetchResult.object(at: index) as PHAsset, targetSize: view.frame.size, contentMode: PHImageContentMode.aspectFill, options: requestOptions, resultHandler: { (image, _) in
            if let image = image {
                // Add the returned image to your array
                self.images += [image]
            }

            if index + 1 < fetchResult.count && self.images.count < totalImageCountNeeded {
                self.fetchPhotoAtIndex(index + 1, totalImageCountNeeded, fetchResult)
            } else {
                // Else you have completed creating your array
                print("Completed array: \(self.images)")

                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.deleteAssets(self.images.first as! NSFastEnumeration)
                }, completionHandler: {success, error in
                    print(success ? "Success" : error?.localizedDescription)
                })
            }
        })
    }

Tochukwu
  • 190
  • 1
  • 11
  • Yes, it's possible. Show us your code so we can help you with it. – matt Jul 15 '19 at 19:21
  • Just know that the user is going to get a massive popup requesting permission to delete that image – CodeBender Jul 15 '19 at 20:10
  • @matt I just added the code I tried. For the records, I have no idea how the code should work – Tochukwu Jul 16 '19 at 08:48
  • You don’t need to request the actual image to delete it. Your whole `fetchPhotoAtIndex` is irrelevant except for `PHAssetChangeRequest.deleteAssets`, that is all you need – matt Jul 16 '19 at 12:20

0 Answers0