I am working on a contacts app and I was wondering if it's possible to search contacts like T9 dealers do (letters associated with each number also filters results). So if I press 2 key, it should search for number '2' as well as 'ABC'.
Code I am trying :
let enteredChar = dialerTextField.text!
var pattern = keysDictionary?[enteredChar.last]
pattern = "[\(String(describing: pattern!.first)) - \(String(describing: pattern!.last))]"
// pattern = "[m-o]" Regex
do {
let matches = items.filter({
(item : String) -> Bool in
let stringMatch = item.range(of: pattern!, options: .regularExpression, range: nil, locale: nil)
return stringMatch != nil ? true : false
})
let predicate = CNContact.predicateForContacts(matchingName: pattern!)
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactImageDataAvailableKey]
var contacts = [CNContact]()
var message: String!
let contactsStore = CNContactStore()
do {
contacts = try contactsStore.unifiedContacts(matching: predicate, keysToFetch: keys as [CNKeyDescriptor])
if contacts.count == 0 {
message = "No contacts were found matching the given name."
}
}
catch {
message = "Unable to fetch contacts."
}
print("matches : ", contacts)
}
catch {
}
using above code I can search for contact name if I change pattern
to say "Rob" but it does not work with Regex "[p-s]"
. I'd like to search with regex. How can this be done? Thank you.
There is no library avaialble that matches exactly what you need.
So
Go to your project and create a new
Custom Keyboard Extension
for your application.This was somewhat matching to your T9 keyboard Tutorial From youtube
This youtube totorial here may help you further
Algorithm to use
Create a dictionary which maps each letter to digits
Like
{"a":1,"b":1,"c":1,"d":2,.. "z":9}
And fetch all contacts and find out the pattern of numbers corresponding to contact names (use the above dictionary for that).
like
{"anna":"2662","baby":"2229","denis":"33647","emila":"36452"}
Whenever the user starts typing on the keyboard, fetch all patters matching in the above dictionary Like if user types
"2"
Corresponding matches will be"anna" and "baby"
.Eliminate the matches when getting more inputs from user.