如何将分页添加到从Photos Framework抓取的PHAsset中? [英] How to add pagination to PHAsset fetching from Photos Framework?

查看:101
本文介绍了如何将分页添加到从Photos Framework抓取的PHAsset中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Photos框架从cameraRoll中获取所有照片,但是要花费很多时间才能从cameraRoll中获取所有照片.

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

            })

        })
    }
}

推荐答案

allPhotos的类型为 PHFetchResult < PHAsset>是一个懒惰的集合,即它实际上不会出去并获得照片,直到您要求它一个照片为止,这是.enumerateObjects所做的.您可以使用下标运算符一次一次抓取照片,或者使用 objects(at :) 获取一系列对象,以分页浏览根据需要收集.

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.

这篇关于如何将分页添加到从Photos Framework抓取的PHAsset中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆