ios - 如何在 swift 3 中通过 SearchBar 按电子邮件地址搜索联系人?

标签 ios swift contacts

我正在通过以下代码从 swift3 的联系人框架中获取联系人

    func getContctFromContactBook(_ completion:  @escaping ContactsHandler) {

    if contactsStore == nil {
        //ContactStore is control for accessing the Contacts
        contactsStore = CNContactStore()
    }

    switch CNContactStore.authorizationStatus(for: CNEntityType.contacts) {
    case CNAuthorizationStatus.denied, CNAuthorizationStatus.restricted:
        //User has denied the current app to access the contacts.

        let productName = Bundle.main.infoDictionary!["CFBundleName"]!

        let alert = UIAlertController(title: "Unable to access contacts", message: "\(productName) does not have access to contacts. Kindly enable it in privacy settings ", preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {  action in
        })
        alert.addAction(okAction)

    case CNAuthorizationStatus.notDetermined:
        //This case means the user is prompted for the first time for allowing contacts
        contactsStore?.requestAccess(for: CNEntityType.contacts, completionHandler: { (granted, error) -> Void in
            //At this point an alert is provided to the user to provide access to contacts. This will get invoked if a user responds to the alert
            if  (!granted ){
                DispatchQueue.main.async(execute: { () -> Void in
                })
            }
            else{
            }
        })
    case  CNAuthorizationStatus.authorized:
        //Authorization granted by user for this app.
        var contactsArray = [CNContact]()

        let contactFetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch as [CNKeyDescriptor])

        do {
            try contactsStore?.enumerateContacts(with: contactFetchRequest, usingBlock: { (contact, stop) -> Void in
                //Ordering contacts based on alphabets in firstname
                contactsArray.append(contact)
            })
            completion(contactsArray, nil)
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

我通过此代码获得了所有联系人,但我的问题是我必须使用谓词通过电子邮件地址从搜索栏中搜索联系人。当我按名称搜索时,我得到了结果,但我不知道如何为电子邮件地址添加谓词。我在下面发布搜索逻辑,请任何人给我建议正确的方法。这是我的搜索逻辑。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if (searchText.characters.count > 0)
{
    let predicate: NSPredicate
    if searchText.characters.count > 0 {
        predicate = CNContact.predicateForContacts(matchingName: searchText)

    } else {
        predicate = CNContact.predicateForContactsInContainer(withIdentifier: contactsStore!.defaultContainerIdentifier())
    }
    let store = CNContactStore()
    do {

        filteredContacts = try store.unifiedContacts(matching: predicate,
                                                     keysToFetch: allowedContactKeys())
    }
    catch {
        print("Error!")
    }
}
else
{
    self.filteredContacts = self.contactsArray
}

 self.tblContact.reloadData()
 }

     func allowedContactKeys() -> [CNKeyDescriptor]{
      //We have to provide only the keys which we have to access. We  should avoid unnecessary keys when fetching the contact. Reducing the keys means faster the access.

    return [CNContactEmailAddressesKey as CNKeyDescriptor,
           CNContactNamePrefixKey as CNKeyDescriptor,
            CNContactGivenNameKey as CNKeyDescriptor,
            CNContactFamilyNameKey as CNKeyDescriptor,
            CNContactOrganizationNameKey as CNKeyDescriptor,
            CNContactBirthdayKey as CNKeyDescriptor,
            CNContactImageDataKey as CNKeyDescriptor,
            CNContactThumbnailImageDataKey as CNKeyDescriptor,
            CNContactImageDataAvailableKey as CNKeyDescriptor,
            CNContactPhoneNumbersKey as CNKeyDescriptor,
    ]
}

最佳答案

你可以这样做

func searchContact(searchString: String) -> [CNContact] {

        //Fetch
        let contactStore: CNContactStore = CNContactStore()
        var contacts: [CNContact] = [CNContact]()
        let fetchRequest: CNContactFetchRequest = CNContactFetchRequest(keysToFetch: [CNContactVCardSerialization.descriptorForRequiredKeys()])

        do {
            try contactStore.enumerateContacts(with: fetchRequest, usingBlock: {
                contact, _ in
                contacts.append(contact) })

        } catch {
            print("Get contacts \(error)")
        }

        //Search
         var resultArray: [CNContact] = [CNContact]()

        for item in contacts {

            for email in item.emailAddresses {
                if email.value.contains(searchString) {
                    resultArray.append(item)
                }
            }
        }

        let withoutDuplicates: [CNContact] = [CNContact](Set(resultArray))
        return withoutDuplicates

}

关于ios - 如何在 swift 3 中通过 SearchBar 按电子邮件地址搜索联系人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44174605/

相关文章:

iphone - 有没有办法处理 UIToolbar 的所有操作?

iPhone : form like new contact

javascript - 添加联系人 Windows 10 通用

swift - 使用未解析的标识符

iphone - 避免在 iPhone 联系人中添加重复条目

iOS UIAlertview 与 uitextview 可编辑

objective-c - 如何检测键盘回车键?

iphone - CoreGraphics 图像调整大小

ios - 当使用 AVPLayer 播放视频时,它会停止背景音乐 ios

ios - 你如何覆盖只读属性以在子类中读写