1

In my swift app, I am retrieving AddressBook contacts from AddressBook framework. Contacts are retrieved successfully except the following case.

Case 1:

If I save a contact number alone without contact name to AddressBook, contact is successfully added.

But, If I try to retrieve that contact which does not having name, App crashes, saying that fatal error received.

Coding:

var contactName: String = ABRecordCopyCompositeName(addressBookRecord).takeRetainedValue() as NSString as String

I don't know how to handle this null value exception. Kindly guide me, how to solve this.

NSNoob
  • 5,548
  • 6
  • 41
  • 54
McDonal_11
  • 3,935
  • 6
  • 24
  • 55

1 Answers1

2

This code will not crash if you got any contact without name:

func processAddressbookRecord(addressBookRecord: ABRecordRef) {

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

    let people:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBookRef).takeRetainedValue();

    for person in people{
        if  let name:String = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String {
            let numbers:ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue()

            if let number:String = ABMultiValueCopyValueAtIndex(numbers,0)?.takeRetainedValue() as? String {
                print("number = \(number)");
                arrayOfContacts.addObject(["\(name)":"\(number)"]);
            }
        }
    }
}

Original post: App crashing while fetching contact numbers from iPhone in SWIFT

Community
  • 1
  • 1
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165