How to sort contacts using Contacts with Swift

后端 未结 2 1232
失恋的感觉
失恋的感觉 2021-01-12 01:53

I\'ve read official apple documentation about sorting contacts, although I am not sure how to implement it. So, here is fetch request:

let fetchRequest = CNC         


        
相关标签:
2条回答
  • 2021-01-12 02:22

    Updated For 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)
            }
    

    Old Version write like this

     fetchRequest.sortOrder = CNContactSortOrder.UserDefault
    

    after fetchRequest object created so your final output is like

    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)
        }
    
    0 讨论(0)
  • 2021-01-12 02:29

    If you are using SwiftyContacts, you can pass in the sort option in the fetchContacts(..) request, see below:

    import SwiftyContacts
    
    fetchContacts(ContactsSortorder: .givenName) { (result) in
        switch result {
        case .success(let contacts):
            print(contacts)
        case .failure(let error):
            print(error)
        }
    }
    
    0 讨论(0)
提交回复
热议问题