从iPhone加载联系人在Swift中崩溃 [英] Loading contacts from iPhone crashes in Swift

查看:58
本文介绍了从iPhone加载联系人在Swift中崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的应用加载联系人。在Simulator中运行正常。但是在iPhone上崩溃了。
我正在使用的代码:

I am trying to load the contacts for my App. It is working fine in Simulator. But crashing in iPhone. The code I am using:

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

此功能正确无误,接触很少后,应用程序崩溃并显示日志:

This function is being correctly and after getting few contacts, the app crashes with log:

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


时意外发现nil

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

I think it is due to Name in contacts, if I try to get the phone number, it is working fine.. I can see all the phone numbers, but in case of Name, i can see around 350 contacts and then app crashes.

有什么办法可以解决吗?

Any idea how I can solve this?

推荐答案

到帐户对于可能的零值(当联系人的记录缺少名称时可能发生),请更改

To account for a potential nil value (which may happen when a contact's record is missing a name), change

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

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

这篇关于从iPhone加载联系人在Swift中崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆