如何使用Swift联系人对联系人进行排序

时间:2016-01-18 09:31:11

标签: ios swift contacts cncontact

我已经阅读了有关排序联系人的官方苹果文档,但我不确定如何实现它。 所以,这是获取请求:

let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

和我最喜欢的排序顺序:

let sortOrder = CNContactSortOrder.UserDefault

这就是我通常获取联系人的方式:

    do {
        try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
                self.contacts.append(contact)
        })
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }

现在我该如何处理sortOrder?我应该在整个提取过程中包含哪些内容?

2 个答案:

答案 0 :(得分:26)

针对Swift 4.0进行了更新

[{"a":"a","b":1,"c":"1","d":"1-1-1-1","e":"Meals"},{"a":"a","b":6,"c":"2","d":"1-1-1","e":"Meals"}]

旧版 像这样写

let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor,CNContactPhoneNumbersKey as CNKeyDescriptor])

        fetchRequest.sortOrder = CNContactSortOrder.userDefault

        let store = CNContactStore()

        do {
            try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in
              //  print(contact.phoneNumbers.first?.value ?? "not found")

            })
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }
创建fetchRequest对象后

所以你的最终输出就像

 fetchRequest.sortOrder = CNContactSortOrder.UserDefault

答案 1 :(得分:0)

如果您使用的是SwiftyContacts,则可以在fetchContacts(..)请求中传递sort选项,如下所示:

import SwiftyContacts

fetchContacts(ContactsSortorder: .givenName) { (result) in
    switch result {
    case .success(let contacts):
        print(contacts)
    case .failure(let error):
        print(error)
    }
}