Photo gallery UIButton with last image/video from gallery iOS

Hi all! I'm trying to make a button with the last image from the gallery of the phone, but it comes with an incomplete size and error.

info.plist

Privacy - Photo Library Additions Usage Description 👌
Privacy - Photo Library Usage Description 👌
Privacy - Media Library Usage Description 👌

ViewModelFile

import Photos

...
    func queryLastPhoto(resizeTo size: CGSize?, queryCallback: @escaping ((UIImage?) -> Void)) {

        let fetchOptions = PHFetchOptions()

        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        let requestOptions = PHImageRequestOptions()

        requestOptions.isSynchronous = true

        let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)

        if let asset = fetchResult.firstObject {

            let manager = PHImageManager.default()

            let targetSize = size == nil ? CGSize(width: asset.pixelWidth, height: asset.pixelHeight) : size!

            manager.requestImage(for: asset,

                                 targetSize: targetSize,

                                 contentMode: .aspectFit,

                                 options: requestOptions,

                                 resultHandler: { image, info in

                                    queryCallback(image)

            })

        }

    }
...

ViewFile (image not resize, but appears )

        viewModel.queryLastPhoto(resizeTo: CGSize(width: 20, height: 20)) { image in
            self.imagePickerButton.setImage(image, for: .normal)
        }

Console output

"Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)""

2021-08-16 10:42:59.018957+0700 MetalFilter[2067:494516] [PAAccessLogger] Failed to log access with error: access=<PATCCAccess 0x283e82ee0> accessor:<<PAApplication 0x283094ba0> identifierType:auditToken identifier:{pid:2067, version:5804} parentApplication:(null)> identifier:4CBF8D4D-ABAB-4A08-BC26-471EBED8DA19 kind:intervalEnd timestampAdjustment:0 tccService:kTCCServicePhotos, error=Error Domain=PAErrorDomain Code=11 "Possibly incomplete access interval automatically ended by daemon"

what am I doing wrong? I hope you'll give me a hand

I got this same error when making a fetchAssets call outside of the main thread.

Try calling your "queryLastPhoto" from the main thread like this:

DispatchQueue.main.async {
    self.queryLastPhoto(to: SIZE) {
        // my callback
    }
}
Photo gallery UIButton with last image/video from gallery iOS
 
 
Q