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

How to sort contacts using Contacts with Swift

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

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 做什么?我应该在整个抓取过程中包含哪些内容?

更新为 Swift 4.0

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.sortOrder = CNContactSortOrder.UserDefault

创建 fetchRequest 对象后 所以你的最终输出就像

let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

fetchRequest.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)
    }

如果你使用SwiftyContacts,你可以在fetchContacts(..)请求中传入排序选项,见下:

import SwiftyContacts

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