CNPropertyNotFetchedException App崩溃

时间:2017-03-29 14:26:57

标签: ios swift contact addressbook

我希望获得手机的所有联系人列表及其名称以及swift 3.0和xcode 8.0中的电话号码。 下面是代码

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) ?? "???")
        }
    }
}

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

1 个答案:

答案 0 :(得分:7)

您正在申请密钥

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

...但是您尝试访问contact.phoneNumber

您只能访问keysToFetch中指定的密钥,因此您需要将CNContactPhoneNumbersKey添加到该阵列