CNPropertyNotFetchedException 应用崩溃

CNPropertyNotFetchedException App Crashed

我想获取 phone 的所有联系人列表及其姓名以及 swift 3.0 和 xcode 8.0 中的 phone 号码。 下面是代码

func get_all_user_contacts()
{
    let status = CNContactStore.authorizationStatus(for: .contacts)
    if status == .denied || status == .restricted
    {
        presentSettingsActionSheet()
        return
    }

    // open it

    let store = CNContactStore()
    store.requestAccess(for: .contacts) { granted, error in
        guard granted else
        {
            DispatchQueue.main.async {
                self.presentSettingsActionSheet()
            }
            return
        }

        // get the contacts

        var contacts = [CNContact]()

        let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as NSString, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
        do
        {
            try store.enumerateContacts(with: request)
            { contact, stop in


                contacts.append(contact)
            }
        }
        catch
        {
            print(error)
        }

        // do something with the contacts array (e.g. print the names)

        let formatter = CNContactFormatter()
        formatter.style = .fullName
        for contact in contacts
        {
            let MobNumVar  = ((contact.phoneNumbers.first?.value)! as CNPhoneNumber).stringValue
            print(MobNumVar)
            print(formatter.string(from: contact) ?? "???")
        }
    }
}

当我 运行 这个应用程序崩溃时,我不知道我哪里出错了。 任何人都可以帮助我。将不胜感激。

您正在请求密钥

• CNContactIdentifierKey
• CNContactFormatter.descriptorForRequiredKeys(for: .fullName)

…但是您正在尝试访问 contact.phoneNumber

您只能访问 keysToFetch 中指定的键,因此您需要将 CNContactPhoneNumbersKey 添加到该数组