Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 483
AAA Avatar asked Aug 11 '15 05:08

AAA


2 Answers

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
like image 110
Lyndsey Scott Avatar answered Sep 30 '22 20:09

Lyndsey Scott


Use the above code it works for me

func readAllPeopleInAddressBook(addressBook: ABAddressBookRef){

/* Get all the people in the address book */
let allPeople = ABAddressBookCopyArrayOfAllPeople(
  addressBook).takeRetainedValue() as NSArray

for person: ABRecordRef in allPeople{


    if(ABRecordCopyValue(person,
        kABPersonFirstNameProperty) != nil){
            let firstName = ABRecordCopyValue(person,
                kABPersonFirstNameProperty).takeRetainedValue() as? String
             println("First name = \(firstName)")
    }

    if (ABRecordCopyValue(person,
        kABPersonLastNameProperty) != nil){

            let lastName = ABRecordCopyValue(person,
                        kABPersonLastNameProperty).takeRetainedValue()as? String
            println("Last name = \(lastName)")
    }



   }
}
like image 40
Mukesh Avatar answered Sep 30 '22 20:09

Mukesh