Null value returns from AddressBook framework in swift

房东的猫 提交于 2020-01-05 11:07:12

问题


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



来源:https://stackoverflow.com/questions/32963845/null-value-returns-from-addressbook-framework-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!