如果应用程序在iOS上不活动,我如何知道联系人已被修改?

时间:2017-01-09 09:23:06

标签: ios swift cncontact cncontactstore

我需要在联系人发生变化时运行一个功能。如果应用程序处于活动状态,您可以使用此post中所述的NotificationCenter来执行此操作(有时,当我向现有联系人添加新号码时,它会起作用)。我如何知道在启动应用程序后联系人(或多个联系人)已被更改?

1 个答案:

答案 0 :(得分:2)

我为我的任务做了以下功能

  @objc private func matchingContacts() {
        if isSuccessContactUploading {
            contactManager.matchingContacts(notMatch: { [weak self] in
                guard let _self = self else { return }
                debugPrint("matchingContacts != equals")
                _self.isSuccessContactUploading = false
                _self.syncContacts()
            })
        }
    }

这些功能在ContactManager中

   func matchingContacts(notMatch: (() -> Void)?) {
        getContacts { (contacts, error) in
            if error == nil {
                debugPrint("contacts count", contacts.count)
                self.getContactsDictionaryFromCache(contacts, notMatch: {
                    notMatch?()
                })
            }
        }
    }

 private func getContactsDictionaryFromCache(_ contacts: [CNContact], notMatch: (() -> Void)?) {
        var isMatching = true
        for contact in contacts {
            let key = contact.identifier

            do {
                let cache = try Cache<NSDictionary>(name: "Contacts")
                if let contactDictionary = cache[key] {
                    if !contactDictionary.isEqual(to: contact.dictionary) {
                        debugPrint("contactDictionary not matching")
                        isMatching = false
                    }
                } else {
                    debugPrint("contactDictionary isn't here")
                    isMatching = false
                }
            } catch {
                debugPrint(error.localizedDescription)
                isMatching = false
            }
        }

        if !isMatching {
            notMatch?()
        }

        cacheContacts(contacts)
    }

private func cacheContacts(_ contacts: [CNContact]) {
        for contact in contacts {
            let contactDictionary = contact.dictionary as NSDictionary
            let key = contact.identifier

            do {
                let cache = try Cache<NSDictionary>(name: "Contacts")
                cache[key] = contactDictionary
            } catch {
                debugPrint(error.localizedDescription)
            }
        }
    }