哪个联系人在您的 iOS 应用外部发生了更改?更好的 CNContactStoreDidChange
通知:获取真实的更改,没有噪音。
遗憾的是,联系人更改 API 一团糟
CNContactStoreDidChange
通知,而不仅仅是应用外部的更改。 🤷userInfo
字段。 🙈这是个被时代遗忘的 API。 🧟♂️
ContactsChangeNotifier
实例 - 它将观察所有通讯录更改,但仅发布来自您应用外部的更改。ContactsChangeNotifier.didChangeNotification
通知。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
}
}
}
pod 'ContactsChangeNotifier'
dependencies: [
.package(url: "https://github.com/yonat/ContactsChangeNotifier", from: "1.2.0")
]