ABRecordCopyValue not working when object doesn't exist

545 views Asked by At

This line of code in Swift causes me problems when the address book has a contact with no last name.

I've tried to resolve it a number of ways to no avail. Is there some sort of try catch statement or error handling I can use? Or check if AnyObject is null (the return type of

ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue()). 

I've tried using optional types but it doesn't seem to work since the app stops running the moment you select a contact with no last name - and the line of code below gets highlighted with the error Thread

1: EXC_BAD_ACCESS

let lName = ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as String
1

There are 1 answers

0
Gus On

ABRecordCopyValue can actually return nil so you should unwrap it. Also, casting to String didn't work for me so I'm using NSString.

if let firstName = ABRecordCopyValue(abContact, kABPersonFirstNameProperty)?.takeRetainedValue() as? NSString {
  println("FIRST NAME: \(firstName)")
}
else {
  println("No Name")
}

Another thing you could try is instead of getting the first and lastName individually, you could also try to get the composed name.

if let fullName = ABRecordCopyCompositeName(abContact)?.takeRetainedValue() as String? {
  println("Full Name: \(fullName)")
}

P.S: I've also tried all the answers from this question but despite of making perfect sense and working when debugging the app, they crashed when I deployed the archive directly into the phone.