PHImageManager 获取请求需要很长时间才能响应
PHImageManager fetch request take long time to response
当我调用此函数从照片中获取最后一张图像时,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
。只需删除该行并在图像到达时对其进行处理(可能多次)。
当我调用此函数从照片中获取最后一张图像时,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
。只需删除该行并在图像到达时对其进行处理(可能多次)。