搜索栏显示正确,但按错了联系人

时间:2018-09-10 12:04:27

标签: ios swift uisearchbar

我已将“搜索栏”添加到“联系人”应用程序中,但是在搜索“姓名”或“姓氏”后返回正确的联系人。但是在媒体上返回的是错误的联系方式。这是我的代码:

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()
            })
        }
    })
}

这是我对搜索栏的功能:

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()
    }
}

更新:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let contact = contactList[indexPath.row]
    let controller = CNContactViewController(for: contact)
    navigationController?.pushViewController(controller, animated: true)
}

1 个答案:

答案 0 :(得分:0)

正如我在上面的评论中所建议的那样,您正在从contactList(或完整的联系人列表)中选择一个项目,但是在搜索模式下,索引显然不会匹配。

您需要检查当前是否显示一组过滤结果,然后根据该信息选择联系人。

也许像这样:

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)
}