How to add pagination to PHAsset fetching from Photos Framework?

前提是你 提交于 2019-12-14 03:59:18

问题


I am trying to get all the photos from cameraRoll using Photos framework but its taking a lot of time to fetch all the photos from cameraRoll.

Is their anyway to add pagination to it ? so i can fetch while scrolling.

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

            })

        })
    }
}

回答1:


allPhotos is of type 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:) to page through the collection as needed.



来源:https://stackoverflow.com/questions/47936192/how-to-add-pagination-to-phasset-fetching-from-photos-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!