PHImageManager获取请求需要很长时间才能响应



当我调用此函数从照片中获取最后一张图像时,UI会被阻塞大约4秒。有什么想法吗?

这是我的代码


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

您所做的是错误和非法的。当您的代码在主线程上运行时,您说的是options.isSynchronous = true。只需删除该行,并在图像到达时对其进行处理(可能多次(。

最新更新