【问题标题】:How to sort contacts using Contacts with Swift如何使用 Swift 的联系人对联系人进行排序
【发布时间】:2016-01-18 09:31:10
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift contacts cncontact


    【解决方案1】:

    为 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)
        }
    

    【讨论】:

    • 我已达到每日投票上限,但这是正确的,谢谢。刚刚删除了CNContactSortOrder.UserDefault 之间的空格。
    • 这个答案太棒了!!谢谢你:)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      相关资源
      最近更新 更多