不征求用户同意从用户通讯录中获取联系人信息

3
我需要从用户的通讯录中获取联系人并在skstableview中显示它。为了获取联系人并在表格视图中显示,我使用了下面的代码。但是,它既没有请求访问联系人权限,也没有获取联系人,并在控制台上打印以下语句:“Access Denied” UserInfo={NSLocalizedDescription=Access Denied, NSLocalizedFailureReason=This application has not been granted permission to access Contacts.}。 我已经在plist文件中添加了访问联系人的条目,但对我来说什么都不起作用。以下是我在Xcode 8.3.3中使用的代码片段,在swift中实现。
 func getContacts() {
    let store = CNContactStore()

    if CNContactStore.authorizationStatus(for: .contacts) == .notDetermined {

        store.requestAccess(for: .contacts){succeeded, err in
            guard err == nil && succeeded else{
                return
            }
            self.contactList()
        }
    } else if CNContactStore.authorizationStatus(for: .contacts) == .authorized {
        self.contactList()
        NSLog(" move to contact list ")

    }
}

func contactList() {
    let req = CNContactFetchRequest(keysToFetch: [
        CNContactFamilyNameKey as CNKeyDescriptor,
        CNContactGivenNameKey as CNKeyDescriptor,
        CNContactPhoneNumbersKey as CNKeyDescriptor
        ])

    arr_contacts.removeAllObjects()

    try! CNContactStore().enumerateContacts(with: req) {
        contact, stop in
        print("contacts \(contact)") // in real life, probably populate an array
        self.arr_contacts.add(contact)
    }

    tbl_List.reloadData()
    print("added all contacts")

}

有人能建议我做错了什么吗?

谢谢


@DávidPásztor 是的,我已经在我的 plist 文件中添加了密钥 Privacy - Contacts Usage Description。 - Chandni
authorizationStatus 的值是什么?请求对话框会向用户显示吗?哪一行抛出了错误 try! CNContactStore().enumerateContacts(with: req) - Dávid Pásztor
@BadhanGanesh 它打印出了这个错误 错误域=CNErrorDomain 代码=100 "访问被拒绝" 用户信息={NSLocalizedDescription=访问被拒绝, NSLocalizedFailureReason=该应用程序未被授权访问联系人。} - Chandni
然后状态可能是“已拒绝”。前往您的应用设置,检查联系人权限是否已关闭。 - badhanganesh
1
@ChandniSharma,你没有指定哪一行代码引发了错误... 但是,如果状态是.denied并且你收到了错误,这意味着在你的代码中的其他地方,你正在调用未经授权检查的contactList。你的问题中的代码似乎没有任何问题,因此错误很可能出现在其他地方。 - Dávid Pásztor
显示剩余7条评论
4个回答

4
请将此内容添加到 info.plist 文件中。
<key>NSContactsUsageDescription</key>
<string>App users your contacts</string>

我已经添加了这个键。 - Chandni

2
Please Add this permission in your info.plist file.

<key>NSContactsUsageDescription</key>
 <string>App users your contacts</string>

1

如果有人遇到以下错误(就像我一样):

This application has not been granted permission to access some of the requested keys.

这可能是因为您在获取联系人时请求了CNContactNoteKey。如果是这种情况,则需要特殊权限才能访问联系人的备注信息:https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_contacts_notes?language=objc

iOS15 beta目前存在一个错误,除非您在获取联系人时请求Notes,否则会引发异常,但是如果您确实请求了Notes,则获取将失败。因此,在iOS15 beta中获取联系人实际上是不可能的,除非您有特殊权限。我已向Apple报告了此问题(FB9263783)。


1
你真是个救命恩人!这正是我的情况! - boxed

0

这个问题出现在模拟器上,但在设备上运行良好,并显示访问权限弹窗。

感谢大家的帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接