问题
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)
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?
回答1:
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
to
let currentContactName = ABRecordCopyCompositeName(currentContact)?.takeRetainedValue() as? String
回答2:
Use the above code it works for me
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)")
}
}
}
来源:https://stackoverflow.com/questions/31933706/loading-contacts-from-iphone-crashes-in-swift