ContactsChangeNotifier

哪个联系人在您的 iOS 应用外部发生了更改?更好的 CNContactStoreDidChange 通知:获取真实的更改,没有噪音。

Swift Version License CocoaPods Compatible Platform PRs Welcome

为什么偏偏要这样

遗憾的是,联系人更改 API 一团糟

这是个被时代遗忘的 API。 🧟‍♂️

ContactsChangeNotifier 功能

用法

  1. 获取用户的“通讯录”访问权限(请参阅 文档)。
  2. 保留 ContactsChangeNotifier 实例 - 它将观察所有通讯录更改,但仅发布来自您应用外部的更改。
  3. 观察 ContactsChangeNotifier.didChangeNotification 通知。
  4. 在通知的 contactsChangeEvents 中查看更改事件。
// 2. Keep a ContactsChangeNotifier instance
let contactsChangeNotifier = try! ContactsChangeNotifier(
    store: myCNContactStore,
    fetchRequest: .fetchRequest(additionalContactKeyDescriptors: myCNKeyDescriptors)
)

// 3. Observe ContactsChangeNotifier.didChangeNotification notification
let observation = NotificationCenter.default.addObserver(
    forName: ContactsChangeNotifier.didChangeNotification,
    object: nil,
    queue: nil
) { notification in
    // 4. See change events in the notification's contactsChangeEvents
    for event in notification.contactsChangeEvents ?? [] {
        switch event {
        case let addEvent as CNChangeHistoryAddContactEvent:
            print(addEvent.contact)
        case let updateEvent as CNChangeHistoryUpdateContactEvent:
            print(updateEvent.contact)
        case let deleteEvent as CNChangeHistoryDeleteContactEvent:
            print(deleteEvent.contactIdentifier)
        default:
            // group event
            break
        }
    }
}

安装

CocoaPods

pod 'ContactsChangeNotifier'

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/yonat/ContactsChangeNotifier", from: "1.2.0")
]