ios - 无法在 iOS 12.4.1 (iPhone XR) 中使用 CNContactStore 获取联系人。即使在 13 beta 或 12.4.1 以下也能正常工作

标签 ios swift xcode ios12 cncontactstore

我正在获取联系人并使用我的自定义 UI 显示它。 我面临一个奇怪的问题,CNContactStore 类没有给我联系人,它返回一个空数组。

下面是我的代码。

let contactStore = CNContactStore()

let keysToFetch = [
        CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
        CNContactGivenNameKey,
        CNContactMiddleNameKey,
        CNContactFamilyNameKey,
        CNContactPhoneNumbersKey
        ] as [Any]

    //Get all the containers
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containers(matching: nil)

    } catch let errorToShow{

        //Handling error
    }

我的代码适用于 12.4.1 以下版本和 iOS 13 所有测试版。现在我正在 iPhone XR 上测试它。

最佳答案

我在未对 info.plist 进行任何更改的情况下尝试了以下代码,它在 iOS 13 及更低版本中运行良好。 (从 iOS 13 开始,我们需要在 plist 中添加 key 才能访问注意,就我而言,我不想这样做)。

 if let keysToFetch = [
            CNContactFormatter.descriptorForRequiredKeys(for: .fullName),CNContactGivenNameKey, CNContactMiddleNameKey,
            CNContactFamilyNameKey,CNContactPhoneNumbersKey] as? [CNKeyDescriptor]{

            let request = CNContactFetchRequest(keysToFetch: keysToFetch)
            do {
                try contactStore.enumerateContacts(with: request){
                    (cont, stop) in
                    // Array containing all unified contacts from everywhere

                }

            } catch let errorToShow{

            }

        }

关于ios - 无法在 iOS 12.4.1 (iPhone XR) 中使用 CNContactStore 获取联系人。即使在 13 beta 或 12.4.1 以下也能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57919221/

相关文章:

ios - UIBarbuttonItem 操作根本不起作用

ios - 如何播放iOS系统声音并取消回调

ios - Swift 和 Objective-c 框架公开其内部结构

ios - Swift 转换,CGFloat 到 Integer

ios - 从设备重新打开应用程序后不显示 NSLog

ios - 在呈现模态视图时显示 UITabBar

ios - Xcode剪贴板: Copy & Paste stuck

ios - Xcode 8 中缺少 "Any"大小类

iphone - iOS : detect UIWebView reaching the top or bottom

ios - 检测 AVPlayerViewController 何时关闭