我已将搜索栏添加到我的联系人应用程序,但在搜索名称或姓氏后返回正确的联系人。但是,记者正在回复错误的联系方式。这是我的代码:
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)
}
正如我在上面的评论中所建议的那样,您正在从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)
}