Home > OS >  PHImageManager fetch request take long time to response
PHImageManager fetch request take long time to response

Time:03-16

When I call this function to get the last image from photos, UI is blocked for around 4 seconds. Any idea for that?

This is my code


import SwiftUI
import Photos

class GalleryManager: NSObject {}

extension GalleryManager {
    func loadLastImageThumb(_ completion: @escaping (UIImage) -> ()) {
        let imgManager = PHImageManager.default()
        let fetchOptions = PHFetchOptions()
        fetchOptions.fetchLimit = 1
        fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: true)]
        
        let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
        
        if let last = fetchResult.lastObject {
            let size = CGSize(width: 100, height: 100)
            let options = PHImageRequestOptions()
            options.resizeMode = .fast
            options.deliveryMode = .fastFormat
            options.isSynchronous = true
            
            imgManager.requestImage(for: last, targetSize: size, contentMode: PHImageContentMode.aspectFill, options: options, resultHandler: { (image, _) in
                if let image = image {
                    completion(image)
                }
            })
        }
    }
}

CodePudding user response:

What you're doing is wrong and illegal. You are saying options.isSynchronous = true when your code runs on the main thread. Just delete that line and deal with the image as it arrives (possibly multiple times).

  • Related