Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从一开始就根据给定字符串搜索联系人_Ios_Swift_Nspredicate_Cncontact - Fatal编程技术网

Ios 从一开始就根据给定字符串搜索联系人

Ios 从一开始就根据给定字符串搜索联系人,ios,swift,nspredicate,cncontact,Ios,Swift,Nspredicate,Cncontact,我想搜索联系人。我能够从“contains”中搜索具有匹配字符串的联系人。但我想搜索根据给定搜索字符串开始的联系人。我的代码是这样的 extension ContactViewController : UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) ->

我想搜索联系人。我能够从“contains”中搜索具有匹配字符串的联系人。但我想搜索根据给定搜索字符串开始的联系人。我的代码是这样的

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

你面临的问题是什么?