Search code examples
iosiphoneswiftcontactsabaddressbook

Loading contacts from iPhone crashes in Swift


I am trying to load the contacts for my App. It is working fine in Simulator. But crashing in iPhone. The code I am using:

func getContactNames()
    {
    let allContacts = ABAddressBookCopyArrayOfAllPeople(addressBookRef).takeRetainedValue() as Array
    for record in allContacts {
        let currentContact: ABRecordRef = record
        let currentContactName = ABRecordCopyCompositeName(currentContact).takeRetainedValue() as String
        if(currentContactName != "") {
                println("found \(currentContactName).")
        }
    }
}

This function is being correctly and after getting few contacts, the app crashes with log:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

I think it is due to Name in contacts, if I try to get the phone number, it is working fine.. I can see all the phone numbers, but in case of Name, i can see around 350 contacts and then app crashes.

Any idea how I can solve this?


Solution

  • To account for a potential nil value (which may happen when a contact's record is missing a name), change

    let currentContactName = ABRecordCopyCompositeName(currentContact).takeRetainedValue() as String
    

    to

    let currentContactName = ABRecordCopyCompositeName(currentContact)?.takeRetainedValue() as? String