Search Bar search through numbers and not only names with Contacts

Traian

New Member
#1
I'm currently trying to search between my contact List and all I can find is looking through names and surnames and not numberPhones. This is my code:
Mã:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == "" {
        inSearchMode = false
        view.endEditing(true)
        self.tableView.reloadData()
    } else {
       inSearchMode = true
       filteredData = contactList.filter {
            $0.givenName.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil ||
            $0.familyName.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil ||
            $0.phoneNumbers.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil
        }
       self.tableView.reloadData()
    }
}
And is giving me error:
Value of type '[CNLabeledValue]' has no member 'range'
How can I solve?
 

Admin

Administrator
Thành viên BQT
#2
The phoneNumbers property of CNContact isn't a String. It's an array of CNLabeledValue objects.

You need to scan the array, extracting the CNPhoneNumber from each CNLabeledValue. Then get the stringValue of the phone number. Finally, use range(of:) on that string value.

Change:
Mã:
$0.phoneNumbers.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil
to:
Mã:
$0.phoneNumbers.contains { $0.value.stringValue.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil }
Note that the first $0 is the CNContact from the contactList array. The second $0 is the CNLabeldValue from the phoneNumbers array of the contact.
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top