如何使用联系人框架在iOS 9中获取所有联系人记录

Jieyi Hu :

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

flohei:

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

相反,您可能要做的是获取所有容器并对其进行迭代以从每个容器中提取所有联系人。以下代码段是如何在其中一个应用程序(在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
}()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章