【问题标题】:How do I know that the contacts have been modified, if the application was not active on iOS?如果应用程序在 iOS 上未激活,我如何知道联系人已被修改?
【发布时间】:2017-01-09 09:23:05
【问题描述】:

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

【问题讨论】:

  • 我认为操作系统不会通知您联系人存储的任何更改。尝试对联系人标识符(或您需要检查已更改的属性)和应用程序启动时进行哈希处理,并在需要时再次对其进行哈希处理。
  • @Sealos 我会这样做,我只是突然想到有一个比这更好的解决方案。

标签: ios swift cncontact cncontactstore


【解决方案1】:

我为我的任务制作了以下函数

  @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)
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 2010-12-08
    • 1970-01-01
    • 2014-12-26
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    相关资源
    最近更新 更多