0

这是我从设备库中获取图像的代码。

let imgManager = PHImageManager.default()
    let requestOptions = PHImageRequestOptions()

    //loading all the images
    requestOptions.isSynchronous = false

    //Quality of the image
    requestOptions.deliveryMode = .highQualityFormat

    //requestOptions.resizeMode = .fast

    //Sorted images
    let fetchOptions = PHFetchOptions()
    fetchOptions.fetchLimit = 500

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

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

 DispatchQueue.global(qos: .background).async {

        if fetchResult.count > 0 {

            DispatchQueue.main.async {
                self.showProgress()
            }

            for i in 0..<fetchResult.count{

                imgManager.requestImage(for: fetchResult.object(at: i) , targetSize: CGSize(width: self.selectedImage.frame.width, height:self.selectedImage.frame.height), contentMode: .aspectFill, options: requestOptions, resultHandler: {
                    image, error in

                    if(image == nil){
                    }else{
                        self.imageArray.append(image!)
                    }
                })
            }

            DispatchQueue.main.async {
                self.hideProgress()
                self.photosCollectionView.reloadData()
            }

        }else{
            self.hideProgress()
            self.showDefaultAlert(title: "Alert", message: "Could not fetch images from the gallery")

        }

当设备中有大约 1500 多个图像时,我会遇到内存问题。我已经想出了如何设置一个限制,当集合视图滚动到底部时如何获取下一个 500 张图像?任何帮助将非常感激。

4

1 回答 1

0

你解决的问题是什么?我认为,重操作在requestImage中,你可以试试

fetchResult.objects(at: IndexSet(0...500))
fetchResult.objects(at: IndexSet(501...1000))

等等,或者可以添加谓词

fetchOptions.predicate = NSPredicate(format: "@NOT(localIdentifier IN %@)", alreadyGettedIdentifiers)

for i in 0..<fetchResult.count{
            let fetchResult = fetchResult.object(at: i)
            alreadyGettedIdentifiers.append(fetchResult.localIdentifier)

            PHImageManager.default().requestImage(for: fetchResult, targetSize: CGSize(width: 200, height:200), contentMode: .aspectFill, options: requestOptions, resultHandler: {
                image, error in

                if(image == nil){
                }else{
                 self.imageArray.append(image!)

                }
            })
        }
于 2017-08-08T13:47:01.267 回答