From 9131cd83fb43821eb27ae6ff5a0e52a07497684f Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Thu, 11 May 2017 12:58:26 -0400 Subject: [PATCH] update contacts only when changed otherwise we're spamming contact intersection all the time // FREEBIE --- .../src/contact/SystemContactsFetcher.swift | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Signal/src/contact/SystemContactsFetcher.swift b/Signal/src/contact/SystemContactsFetcher.swift index 2eda10aa1..808a51fb5 100644 --- a/Signal/src/contact/SystemContactsFetcher.swift +++ b/Signal/src/contact/SystemContactsFetcher.swift @@ -14,6 +14,7 @@ import ContactsUI class SystemContactsFetcher: NSObject { private let TAG = "[SystemContactsFetcher]" + var lastContactUpdateHash: Int? public weak var delegate: SystemContactsFetcherDelegate? @@ -125,6 +126,19 @@ class SystemContactsFetcher: NSObject { } let contacts = systemContacts.map { Contact(systemContact: $0) } + + let contactsHash = HashableArray(contacts).hashValue + guard (self.lastContactUpdateHash != contactsHash) else { + Logger.debug("\(self.TAG) System contacts unchanged. hash:\(contactsHash)") + DispatchQueue.main.async { + completion?(nil) + } + return + } + self.lastContactUpdateHash = contactsHash + + Logger.debug("\(self.TAG) Notifying delegate that system contacts did change. hash:\(contactsHash)") + DispatchQueue.main.async { self.delegate?.systemContactsFetcher(self, updatedContacts: contacts) completion?(nil) @@ -145,3 +159,22 @@ class SystemContactsFetcher: NSObject { } } + +struct HashableArray: Hashable { + var elements: [Element] + init(_ elements: [Element]) { + self.elements = elements + } + + var hashValue: Int { + // random generated 32bit number + let base = 224712574 + return elements.reduce(base) { (result, element) -> Int in + return result ^ element.hashValue + } + } + + static func == (lhs: HashableArray, rhs: HashableArray) -> Bool { + return lhs.hashValue == rhs.hashValue + } +}