如何使用Contacts Framework获取iOS 9中的所有联系人记录 [英] How to fetch all contacts record in iOS 9 using Contacts Framework

查看:515
本文介绍了如何使用Contacts Framework获取iOS 9中的所有联系人记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS 9中不推荐使用AddressBook框架的大部分内容。在新的Contacts Framework中文档仅显示如何获取与 NSPredicate 匹配的记录,但如果我想要所有,该怎么办?记录?

Most part of AddressBook framework is deprecated in iOS 9. In the new Contacts Framework documentation only shows how to fetch records matches a NSPredicate, but what if I want all the record?

推荐答案

其他答案只会使用 defaultContainerIdentifier 。在用户具有多个容器(即,Exchange和iCloud帐户都用于存储联系人)的情况下,这将仅加载来自配置为默认帐户的联系人。因此,它不会按照问题作者的要求加载所有联系人。

Both other answers do only load contacts from the container with the defaultContainerIdentifier. In a scenario, where the user has more than one container (i.e. an Exchange and an iCloud account which both are used to store contacts), this would only load the contacts from the account that is configured as the default. Therefore, it would not load all contacts as requested by the author of the question.

您可能想要做的事情就是获取所有容器并迭代它们以从每个容器中提取所有联系人。以下代码片段是我们在其中一个应用程序(在Swift中)中执行此操作的示例:

What you'll probably want to do instead is getting all the containers and iterate over them to extract all contacts from each of them. The following code snippet is an example of how we do it in one of our apps (in Swift):

lazy var contacts: [CNContact] = {
    let contactStore = CNContactStore()
    let keysToFetch = [
        CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
        CNContactEmailAddressesKey,
        CNContactPhoneNumbersKey,
        CNContactImageDataAvailableKey,
        CNContactThumbnailImageDataKey]

    // Get all the containers
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containersMatchingPredicate(nil)
    } catch {
        print("Error fetching containers")
    }

    var results: [CNContact] = []

    // Iterate all containers and append their contacts to our results array
    for container in allContainers {
        let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)

        do {
            let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
            results.appendContentsOf(containerResults)
        } catch {
            print("Error fetching results for container")
        }
    }

    return results
}()

这篇关于如何使用Contacts Framework获取iOS 9中的所有联系人记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆