是否可以使用swift删除照片库中的最后一张照片

时间:2019-07-15 19:15:29

标签: ios swift screenshot delete-file phphotolibrary

我正在尝试从我的照片库中获取最后一张图像并将其删除。 关于获取最后一张图片的答案,以及使用其网址删除图片的答案,但是我发现很难将两者合并在一起


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)
                })
            }
        })
    }

0 个答案:

没有答案
相关问题