在iPhone中加载来自iPhone的联系人崩溃

时间:2015-08-11 05:13:16

标签: ios iphone swift contacts abaddressbook

我正在尝试为我的应用加载联系人。它在模拟器中工作正常。但在iPhone中崩溃。 我正在使用的代码:

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).")
        }
    }
}

此功能正常,在获得少量联系后,应用程序崩溃并显示日志:

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

我认为这是由于姓名中的联系人,如果我尝试获取电话号码,它工作正常..我可以看到所有的电话号码,但如果是姓名,我可以看到大约350个联系人然后应用程序崩溃。

知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:9)

要考虑潜在的零值(当联系人的记录缺少名称时可能会发生这种情况),请更改

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

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

答案 1 :(得分:2)

使用上面适合我的代码

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)")
    }



   }
}