照片库更改时的Swift观察者模式

时间:2016-08-04 09:34:00

标签: ios swift camera-roll

目前,我有这段代码:

import Photos

public class AssetService : NSObject, PHPhotoLibraryChangeObserver {

public override init() {
    super.init()
    PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
}

deinit {
    PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self)
}

public func photoLibraryDidChange(changeInstance: PHChange) {

    dispatch_async(dispatch_get_main_queue(), {

    })

}  


}

如果我想查看相机胶卷中的更新,我可以在photoLibraryDidChange功能中执行哪些操作。我将开头的所有图像/视频提取到PHFetchResult中,现在我想监视更改 我总是在全屏显示UIView中的图像/视频,并使用UIPageControl滚动内容。感谢任何帮助

1 个答案:

答案 0 :(得分:3)

来自https://developer.apple.com/library/prerelease/content/samplecode/UsingPhotosFramework/Listings/Shared_MasterViewController_swift.html#//apple_ref/doc/uid/TP40014575-Shared_MasterViewController_swift-DontLinkElementID_9

var allPhotos: PHFetchResult<PHAsset>!
var smartAlbums: PHFetchResult<PHAssetCollection>!
var userCollections: PHFetchResult<PHCollection>!

func photoLibraryDidChange(_ changeInstance: PHChange) {
    // Change notifications may be made on a background queue. Re-dispatch to the
    // main queue before acting on the change as we'll be updating the UI.
    DispatchQueue.main.sync {
        // Check each of the three top-level fetches for changes.

        if let changeDetails = changeInstance.changeDetails(for: allPhotos) {
            // Update the cached fetch result. 
            allPhotos = changeDetails.fetchResultAfterChanges 
            // (The table row for this one doesn't need updating, it always says "All Photos".)
        }

        // Update the cached fetch results, and reload the table sections to match.
        if let changeDetails = changeInstance.changeDetails(for: smartAlbums) {
            smartAlbums = changeDetails.fetchResultAfterChanges
            tableView.reloadSections(IndexSet(integer: Section.smartAlbums.rawValue), with: .automatic)
        }
        if let changeDetails = changeInstance.changeDetails(for: userCollections) {
            userCollections = changeDetails.fetchResultAfterChanges
            tableView.reloadSections(IndexSet(integer: Section.userCollections.rawValue), with: .automatic)
        }

    }
}