Null value returns from AddressBook framework in s

2019-08-07 01:39发布

问题:

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.

回答1:

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