Search Bar displaying correct but on press wrong Contact

Traian

New Member
#1
I've added the Search Bar to my Contact application but after searching for the Name or the Surname is returning the correct contact. But on press is returning the wrong contact. Here is my code:
Mã:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let store = CNContactStore()
    store.requestAccess(for: .contacts, completionHandler: { (success, error) in
        if success {
            let keys = CNContactViewController.descriptorForRequiredKeys()
            let request = CNContactFetchRequest(keysToFetch: [keys])

            request.sortOrder = CNContactSortOrder.givenName

            do {
                self.contactList = []
                try store.enumerateContacts(with: request, usingBlock: { (contact, status) in
                    self.contactList.append(contact)
                })
            } catch {
                print("Error")
            }
            OperationQueue.main.addOperation({
            self.tableView.reloadData()
            })
        }
    })
}
And this is my function for the search bar:
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
        }
       self.tableView.reloadData()
    }
}
UPDATE:
Mã:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let contact = contactList[indexPath.row]
    let controller = CNContactViewController(for: contact)
    navigationController?.pushViewController(controller, animated: true)
}
 

Admin

Administrator
Thành viên BQT
#2
As suggested in my comment above, you are selecting an item from the contactList (or full list of contacts) but when in search mode the indexes obviously wont match up.

You need to check whether your currently displaying a filtered set of results or not and then select the contact based on that info.

Maybe something like:

Mã:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    var contact: CNContact

    if inSearchMode {
        contact = filteredData[indexPath.row]
    } else {
        contact = contactList[indexPath.row]
    }

    let controller = CNContactViewController(for: contact)
    navigationController?.pushViewController(controller, animated: true)
}
 
Top