【问题标题】:Loading contacts from iPhone crashes in Swift在 Swift 中从 iPhone 加载联系人崩溃
【发布时间】:2015-08-11 05:13:16
【问题描述】:

我正在尝试为我的应用加载联系人。它在模拟器中运行良好。但在 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 个联系人,然后应用程序崩溃。

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

【问题讨论】:

    标签: ios iphone swift contacts abaddressbook


    【解决方案1】:

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

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

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

    【讨论】:

    • 啊...谢谢。 :)
    【解决方案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)")
        }
    
    
    
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      相关资源
      最近更新 更多