如何为从 Photos Framework 获取的 PHAsset 添加分页?

How to add pagination to PHAsset fetching from Photos Framework?

我正在尝试使用照片框架从 cameraRoll 获取所有照片,但是从 cameraRoll 获取所有照片需要花费大量时间。

他们是否要为其添加分页? 所以我可以在滚动时获取。

 var images = [UIImage]()
 var assets = [PHAsset]()

fileprivate func assetsFetchOptions() -> PHFetchOptions {
    let fetchOptions = PHFetchOptions()

    //fetchOptions.fetchLimit = 40 //uncomment to limit photo

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

fileprivate func fetchPhotos() {
    let allPhotos = PHAsset.fetchAssets(with: .image, options: assetsFetchOptions())

    DispatchQueue.global(qos: .background).async {
        allPhotos.enumerateObjects({ (asset, count, stop) in
            //print(count)

            let imageManager = PHImageManager.default()
            let targetSize = CGSize(width: 200, height: 200)
            let options = PHImageRequestOptions()
            options.isSynchronous = true
            imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: options, resultHandler: { (image, info) in

                if let image = image {
                    self.images.append(image)
                    self.assets.append(asset)
                }

                if count == allPhotos.count - 1 {
                    DispatchQueue.main.async {
                        self.collectionView?.reloadData()
                    }
                }

            })

        })
    }
}

allPhotos 属于 PHFetchResult< PHAsset > which is a lazy collection, ie it doesn't actually go out and get the photo until you ask it for one, which is what .enumerateObjects is doing. You can just grab the photos one at a time with the subscript operator or get a range of objects with objects(at:) 类型,可根据需要在集合中分页。