I just want to get contact given name and family name by phone number. I tried this but this is too much slow and cpu is hitting over %120.
let contactStore = CNContactStore()
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
var contacts = [CNContact]()
do {
try contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest.init(keysToFetch: keys), usingBlock: { (contact, cursor) in
if (!contact.phoneNumbers.isEmpty) {
for phoneNumber in contact.phoneNumbers {
if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber {
do {
let libPhone = try util.parseWithPhoneCarrierRegion(phoneNumberStruct.stringValue)
let phoneToCompare = try util.getNationalSignificantNumber(libPhone)
if formattedPhone == phoneToCompare {
contacts.append(contact)
}
}catch {
print(error)
}
}
}
}
})
if contacts.count > 0 {
contactName = (contacts.first?.givenName)! + " " + (contacts.first?.familyName)!
print(contactName)
completionHandler(contactName)
}
}catch {
print(error)
}
Also When I Use phonenumber Kit for find contacts its increasing cpu and giving late response.
var result: [CNContact] = []
let nationalNumber = PhoneNumberKit().parseMultiple([phoneNumber])
let number = nationalNumber.first?.toNational()
print(number)
for contact in self.addressContacts {
if (!contact.phoneNumbers.isEmpty) {
let phoneNumberToCompareAgainst = number!.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
for phoneNumber in contact.phoneNumbers {
if let phoneNumberStruct = phoneNumber.value as? CNPhoneNumber {
let phoneNumberString = phoneNumberStruct.stringValue
let nationalContactNumber = PhoneNumberKit().parseMultiple([phoneNumberString])
let nationalContactNumberString = nationalContactNumber.first?.toNational()
if nationalContactNumberString == number {
result.append(contact)
}
}
}
}
}
return result