alex alex - 5 years ago 198
Swift Question

While adding let addressBookRef: ABAddressBook i get a crash error?

I am trying to add a simple add to contacts feature.

Just adding the variable

let addressBookRef: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()


in an existing DetailViewController class and my project crashes:

fatal error: unexpectedly found nil while unwrapping an Optional value


Just outcommenting the addressBookRef and my project doesn't crash

Is it because i have the variable in a detailviewcontroller from my main view?

I am following this tutorial, http://www.raywenderlich.com/97936/address-book-tutorial-swift-ios

[EDIT]
I also have

@IBAction func addToContacts(sender: AnyObject) {
let authorizationStatus = ABAddressBookGetAuthorizationStatus()

switch authorizationStatus {
case .Denied, .Restricted:
//1
print("Denied")
case .Authorized:
//2
print("Authorized")
case .NotDetermined:
//3
print("Not Determined")
//promptForAddressBookRequestAccess(addContacts)
}

print("Add to contacts")
}


and when i outcomment the variable and just check what the case is i see "Denied" but i expect "Not Determined", why the denied??

[EDIT]
WOW, that's a pain in the..... i have spent 1 hour to get the prompt and the one thing that work was:
Delete App -> Restart iPhone -> set date/time 2 days ahead -> Restart iPhone -> compile App again

Other suggestions i didn't try:
1/ unique build number
2/ Settings --> General--> Reset--> Reset Location&Privacy

iOS resetting granting access to reminders

Answer Source

It is because ABAddressBookCreateWithOptions is returning nil so calling takeRetainedValue() on it causes the error.

ABAddressBookCreateWithOptions will return nil is the user has not allowed you app to access contacts. You will need to use ABAddressBookGetAuthorizationStatus to determine if the app has permission before creating an address book.


Edit

It sounds like when the permissions alert was shown, disallow was pressed.

You need to open the Settings app, scroll down and tap on the name of your app, the change the switch next to "Contacts" to be on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download