在swift中实现PHPhotoLibraryChangeObserver协议

时间:2016-03-03 16:49:16

标签: swift photosframework swift-protocols

我尝试将AssetService设置为changeObserver,但是我收到了以下错误:

Error:(8, 14) type 'AssetService' does not conform to protocol 'PHPhotoLibraryChangeObserver'

虽然photoLibraryDidChange是唯一必需的方法。这是我的代码:

import UIKit
import Photos

public class AssetService : PHPhotoLibraryChangeObserver {

    public init() {

        // here I do some other stuff
        PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
    }

    public func photoLibraryDidChange(changeInstance: PHChange) {
        dispatch_async(dispatch_get_main_queue(), {

        })
    }
}

2 个答案:

答案 0 :(得分:1)

我认为您需要从NSObject扩展才能在PhotoFramework中使用它

因此,您还需要覆盖init并添加super.init()

import UIKit 
import Photos

public class AssetService : NSObject, PHPhotoLibraryChangeObserver {
     public override init() {
         super.init()
         // here I do some other stuff
         PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
     }

    public func photoLibraryDidChange(changeInstance: PHChange) {
        dispatch_async(dispatch_get_main_queue(), {

        })
    }
}

希望这会解决它

答案 1 :(得分:1)

在Swift 3.0中,寄存器实际上现在看起来像这样:

func photoLibraryDidChange(_ changeInstance: PHChange) {
    DispatchQueue.main.async {

    }
}

public override init() {
    super.init()
    PHPhotoLibrary.shared().register(self)
}

Bart Schoon's answer

中的其他所有内容都相同