Ios 从一开始就根据给定字符串搜索联系人
我想搜索联系人。我能够从“contains”中搜索具有匹配字符串的联系人。但我想搜索根据给定搜索字符串开始的联系人。我的代码是这样的Ios 从一开始就根据给定字符串搜索联系人,ios,swift,nspredicate,cncontact,Ios,Swift,Nspredicate,Cncontact,我想搜索联系人。我能够从“contains”中搜索具有匹配字符串的联系人。但我想搜索根据给定搜索字符串开始的联系人。我的代码是这样的 extension ContactViewController : UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) ->
extension ContactViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let searchString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if searchString == ""
{
contacts = allContacts
}
else
{
do {
let predicate: NSPredicate = CNContact.predicateForContacts(matchingName: searchString)
let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactImageDataKey,CNContactPhoneNumbersKey,CNContactImageDataAvailableKey] as [Any]
self.contacts = try self.contactStore.unifiedContacts(matching: predicate, keysToFetch:keys as! [CNKeyDescriptor])
}
catch {
print("Unable to refetch the selected contact.")
}
}
//contacts = filterContactArray(contact: contacts)
self.tableContact.reloadData()
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
所以请帮我解决这个问题。提前感谢。这里是将谓词与CNContact一起使用的解决方案
let predicates = NSPredicate(format: CNContactGivenNameKey + " BEGINSWITH[cd] %@", searchString)
contacts = (allContacts as NSArray).filtered(using: predicates) as! [CNContact]
tableContact.reloadData()
你面临的问题是什么?