I want to display only those contacts with particular phone numbers. The phone numbers are written in an array. I don't know how to display only these contacts. Therefore I tried to use the "predicateForEnablingContact" Method. But with my code, all contacts are disabled, even the ones with the right number. I am using the Contacts Framework. Help would be much appreciated.
func picker () {
let numbers = ["555","8885555512"]
let pick = CNContactPickerViewController()
pick.displayedPropertyKeys = [CNContactPhoneNumbersKey]
pick.predicateForEnablingContact = NSPredicate(format: "phoneNumbers = %@", argumentArray: numbers)
pick.delegate = self
presentViewController(pick, animated: true, completion: nil)
}
func contactPicker(picker: CNContactPickerViewController, didSelectContacts contacts: [CNContact]) {
let Kontakte = contacts
print(Kontakte)
dismissViewControllerAnimated(true, completion: nil)
}
This code returns only the contacts that have a phone number in the given set:
let numbers = Set(["555","8885555512"])
let predicate = NSPredicate { (evaluatedObject, bindings) -> Bool in
guard let evaluatedContact = evaluatedObject as? CNContact else { return false }
return Set(evaluatedContact.phoneNumbers.map{ return ($0.value as! CNPhoneNumber).stringValue }).intersect(numbers).count > 0
}
Note that numbers
is a Set. This is in order to use the intersect
method later on. intersect
is used to determine if the contact shares any phone numbers with the given numbers; if so, then the predicate results in true
.
I used the KPKContacts package
Its as simple as calling this method
var contacts: [KPKContact]()
let contactStore = KPKContactStore()
//make sure you implement the delegate method that will notify contact authorisation changes
contactStore.delegate = self
self.kpkContactStore.findContactsWithValidNumbersOnly(){
kpkContacts in
if let contacts = kpkContacts {
self.contacts = contacts
self.tableView.reloadData()
}
}
It comes with a default regex to phone numbers formatted as ### ### ###, ###-###-###, (###) ###-####, #-###-###-###, ###-###-###, #########
You can alternatively get your own regex from regex resources and edit the PHONE_REGEX property in this method
private var regexPhoneNumberValidatorBlock: String -> Bool = { value in
let PHONE_REGEX = "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluateWithObject(value)
return result
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.