5

我有以下代码:

override func viewDidLoad() {
    ........
    PHPhotoLibrary.shared().register(self)
}

我已经实施了PHPhotoLibraryDidChangeObserver.

我的问题是,photoLibraryDidChange如果设备库中的某些内容发生变化,该方法会被多次调用。
这是该函数的代码:

func photoLibraryDidChange(_ changeInstance: PHChange) {
    DispatchQueue.main.async(execute: {
        self.updateFetchResult();
    })
}

你知道为什么这个方法会执行multiple多次吗?

4

3 回答 3

0
extension YourViewController: PHPhotoLibraryChangeObserver {

    func photoLibraryDidChange(_ changeInstance: PHChange) {
        if let _fetchResult = self.fetchResult, let resultDetailChanges = changeInstance.changeDetails(for: _fetchResult) {
            let addedItems = resultDetailChanges.insertedObjects
            let deletedItems = resultDetailChanges.removedObjects
            let changedItems = resultDetailChanges.changedObjects
            if resultDetailChanges.hasIncrementalChanges && (addedItems.count > 0 || deletedItems.count > 0 || changedItems.count > 0){
                DispatchQueue.main.async {
                    self.getPhotos()
                }
            }
        }
    }

}

以上resultDetailChanges.hasIncrementalChanges对(添加、删除、更改的资产)的检查和计数将避免多次调用。

于 2018-05-30T15:27:57.057 回答
0

试试这个方法

extension YourViewController: PHPhotoLibraryChangeObserver {

        func photoLibraryDidChange(_ changeInstance: PHChange) {
            if let _fetchResult = self.fetchResult, let resultDetailChanges = changeInstance.changeDetails(for: _fetchResult) {
                let insertedObjects = resultDetailChanges.insertedObjects
                let removedObjects = resultDetailChanges.removedObjects
                let changedObjects = resultDetailChanges.changedObjects.filter( {
                    return changeInstance.changeDetails(for: $0)?.assetContentChanged == true
                })
                if resultDetailChanges.hasIncrementalChanges && (insertedObjects.count > 0 || removedObjects.count > 0 || changedObjects.count > 0){
                    DispatchQueue.main.async {
                        self.getPhotos()
                    }
                }
            }
        }

    }
于 2020-05-27T08:52:24.707 回答
0

你找到解决方案了吗?这解决了mi问题:

首先,如果您使用此方法,请PHFetResult<PHAsset>在调用时保存。PHAsset.fetchAssets(with:options:)

之后,使用您的PHFetResult<PHAsset>变量来验证获取结果是否在photoLibraryDidChange:方法中发生了变化。第一次调用此方法时,您必须更新为集合视图或表格视图。之后,您的获取结果没有改变,所以......您没有什么要更新的。

这是我的完整代码:

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

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

.
.
.

extension YourViewController: PHPhotoLibraryChangeObserver {

    func photoLibraryDidChange(_ changeInstance: PHChange) {
        if let _fetchResult = self.fetchResult, let _ = changeInstance.changeDetails(for: _fetchResult) {
            DispatchQueue.main.async {
                self.getPhotos()
            }
        }
    }

}

希望这对你有帮助!

于 2017-07-07T16:39:27.780 回答