9

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

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?我应该在哪里以及应该在我的整个获取过程中包括哪些内容?

4

2 回答 2

32

为 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)
    }
于 2016-01-18T09:42:08.983 回答
0

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

import SwiftyContacts

fetchContacts(ContactsSortorder: .givenName) { (result) in
    switch result {
    case .success(let contacts):
        print(contacts)
    case .failure(let error):
        print(error)
    }
}
于 2020-10-08T19:16:51.890 回答