ios - 从图库中获取图像很慢

标签 ios swift image photosframework

<分区>

当我试图从我的图库中获取 10 张图片时,我需要很长时间才能获取。

  1. 为什么图像获取是异步的?
  2. 如果我将 requestOptions.deliveryMode 更改为 .fastFormat,它会变得很快,但我会失去质量

我能做的最好的是什么?

func fetchPhotos() {
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    fetchOptions.fetchLimit = 10

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

    if fetchResult.count > 0 {
        let totalImageCountNeeded = 10 // <-- The number of images to fetch
        fetchPhotoAtIndex(0, totalImageCountNeeded, fetchResult)
    }
}

func fetchPhotoAtIndex(_ index:Int, _ totalImageCountNeeded: Int, _ fetchResult: PHFetchResult<PHAsset>) {

    let requestOptions = PHImageRequestOptions()
    requestOptions.deliveryMode = .highQualityFormat

    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 {
            print("Completed array: \(self.images)")
            self.collectionView.reloadData()
        }
    })
}

最佳答案

我刚刚测试了您的代码,加载 50 张图片大约需要一秒钟,请检查您的代码中是否有其他内容可能会减慢此过程。 如果您的意图是在显示 View Controller 时立即加载所有图像,请考虑在上一个屏幕上加载图像。

关于ios - 从图库中获取图像很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56297431/

相关文章:

ios - ARSCNView 截图

javascript - AngularJS 向 iOS WKWebView 发送消息

php - 推特分享并附有图片

image - Tensorflow.js:将图像调整为特定字节大小

ios - 在iOS中检测音频文件中的间隙

ios - 使用 UIWebView (iOS) 无法自动登录 Google+?

swift - UIlabel 动画不适合屏幕

ios - 以编程方式添加的按钮目标操作在自定义 tableviewcell 中不起作用

swift - 将 float3 从 Swift 结构传递到 Metal 着色器

php - 安卓 : Image uploaded to server is always 0 bytes