How to retrieve all contacts using CNContact.predicateForContacts?
I'd like to retrieve all the names of the people listed on address book.
Form a CNContactFetchRequest specifying that the keys you want are names, and call enumerateContacts(with:usingBlock:)
.
let req = CNContactFetchRequest(keysToFetch: [
CNContactFamilyNameKey as CNKeyDescriptor,
CNContactGivenNameKey as CNKeyDescriptor
])
try! CNContactStore().enumerateContacts(with: req) {
contact, stop in
print(contact) // in real life, probably populate an array
}
set correct CNContact.predicateForContacts to select email
Your predicate is trying to find contacts where the person's name matches the string lbs
.
There is no built-in predicate for finding contacts that have an email address containing a specific string. The solution is to use enumerateContacts
and look at each individual contact's list of email addresses. You will then need to check to see if any of the contact's email address contains the string you wish to check.
phone number predicate on CNContactStore
In short: you can't create a predicate to filter based on phone number. You have to pull all of the contacts and iterate. NOTE: For any given phone number, it 1) may not exist in contacts, or 2) exist more than once.
Check out this post:
https://forums.developer.apple.com/thread/19329
How to fetch contacts NOT named John with Swift 3
Before I outline how to find those that don't match a name, let's recap how one finds those that do. In short, you'd use a predicate:
let predicate = CNContact.predicateForContacts(matchingName: searchString)
let matches = try store.unifiedContacts(matching: predicate, keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]) // use whatever keys you want
(Obviously, you'd wrap that in a do
-try
-catch
construct, or whatever error handling pattern you want.)
Unfortunately, you cannot use your own custom predicates with the Contacts framework, but rather can only use the CNContact
predefined predicates. Thus, if you want to find contacts whose name does not contain "John", you have to manually enumerateContacts(with:)
and build your results from that:
let formatter = CNContactFormatter()
formatter.style = .fullName
let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]) // include whatever other keys you may need
// find those contacts that do not contain the search string
var matches = [CNContact]()
try store.enumerateContacts(with: request) { contact, stop in
if !(formatter.string(from: contact)?.localizedCaseInsensitiveContains(searchString) ?? false) {
matches.append(contact)
}
}
Matching CNcontact and Digits Find Friends Swift 3
Ideally, one would have expected predicate
of the CNContactFetchRequest
to do the job, but that (still; argh) only accepts a narrow list of predicates defined with CNContact
(e.g. CNContact
predicateForContacts(matchingName:)
or predicateForContacts(withIdentifiers:)
. It doesn't even accept the block-based NSPredicate
.
So, you have to enumerate through, looking for matches yourself, e.g.
let request = CNContactFetchRequest(keysToFetch: [
CNContactGivenNameKey as CNKeyDescriptor,
CNContactFamilyNameKey as CNKeyDescriptor,
CNContactMiddleNameKey as CNKeyDescriptor,
CNContactEmailAddressesKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor
])
do {
try contactStore.enumerateContacts(with: request) { contact, stop in
for phone in contact.phoneNumbers {
// look at `phone.value.stringValue`, e.g.
let phoneNumberDigits = String(phone.value.stringValue.characters.filter { String($0).rangeOfCharacter(from: CharacterSet.decimalDigits) != nil })
if phoneNumberDigits == "8885551212" {
self.results.append(contact)
return
}
}
}
} catch let enumerateError {
print(enumerateError.localizedDescription)
}
Regarding matching "digit UserID", I don't know what that identifier is (is it a Contacts framework identifier or Digits' own identifier?).
Related Topics
Firebase References Undeclared
Formsheet iOS 8 Constraints Are Same as Iphones Constraints
String Comparison in Swift Is Not Transitive
Swift Extension Storage for Protocols
Swift Combine Publishers VS Completion Handler and When to Cancel
How to Do a Long Press in Swift
Typecast Unsafemutablepointer<Void> to Unsafemutablepointer<#Struct Type#>
Swiftlint Overriding Project Settings Related to Spm
Does Untimeintervalnotificationtrigger Nexttriggerdate() Give the Wrong Date
Why Does Type(Of:) Return Metatype, Rather Than T.Type
How to Add Multiple Values for One Key in a Dictionary Using Swift
Removing a Closure from an Array
Weak Method Argument Semantics
iOS Swift Didbegincontact Not Being Called