How to add pagination to PHAsset fetching from Pho

2019-08-01 02:03发布

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条回答
神经病院院长
2楼-- · 2019-08-01 02:08

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.

查看更多
登录 后发表回答