Reputation: 3833
I am trying to gain access to the phone's contacts with the code below but the user isn't prompted to give me permission.
let store = CNContactStore()
store.requestAccessForEntityType(.Contacts) { granted, error in
guard granted else {
dispatch_async(dispatch_get_main_queue()) {
// user didn't grant authorization, so tell them to fix that in settings
print("error accessing adress book %@",error)
}
return
}
print("Access granted to adress book")
// get the contacts
var contacts = [CNContact]()
let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)])
do {
try store.enumerateContactsWithFetchRequest(request) { contact, stop in
contacts.append(contact)
}
} catch {
print(error)
}
//TODO : Do something with the contacts
let formatter = CNContactFormatter()
formatter.style = .FullName
for contact in contacts {
print(formatter.stringFromContact(contact))
}
}
Upvotes: 0
Views: 456
Reputation: 795
Can you please elaborate what is the exact error?
I tried your code on a iOS 9.2.1 device and the code seems to be working fine. I got the "Access granted to adress book" log and the contacts information.
You should check device permission at Setings->Privacy->Contacts, if you are facing Error Domain=CNErrorDomain Code=100 "Access Denied" error.
Just in case, if you clicked "Dont Allow" on the Contact access permission prompt and now as the preference has got saved and you are not getting the prompt, then you can change your bundle identifier to test your code.
If you need to reset all privacy settings: https://stackoverflow.com/a/12596350/4209778
Upvotes: 1