CNPropertyNotFetchedException应用程序崩溃
问题描述:
我想要得到他们的名字以及swift 3.0和xcode 8.0中的电话号码的手机的所有联系人列表。下面 是代码CNPropertyNotFetchedException应用程序崩溃
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
到阵列
+0
是的。你是对的。但可以帮助我更多,我可以如何将其添加到数组。 ???一些代码.. thnx –
+0
它的工作原理。我添加了:CNContactPhoneNumbersKey作为CNKeyDescriptor –
它在哪里崩溃?你收到什么信息? –