我只想通过电话号码联系姓名和姓氏 . 我试过这个,但这太慢了,cpu超过%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)
}
另外,当我使用phonenumber Kit查找联系人时,它会增加cpu并给出延迟响应 .
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
2 回答
您的实施问题是您在每次搜索时访问地址簿 .
相反,如果您在第一次访问后保留内存中的地址簿内容,则不会达到此高CPU使用率 .
.
I tested it with a very big address book, it works smoothly.
这是整个视图控制器拼凑在一起以供参考 .
我使用flohei's answer作为懒惰的var部分 .
SWIFT 4 UPDATE
1)添加到.plist
2)如果您没有请求授权
2)如果您之前要求,请检查授权状态
3)致电获取联系人
4) THIS IS THE FUNCTION TO GET THE CONTACT NAME OR BY NUMBER