Reputation: 1647
I am creating an application where it is needed to add a contact to the address book of that device. When I am adding the contact to the device using only the first and last name, everything is going fine. However when I am trying to add the phone number as well, the app crashes. Can anybody see what I am doing wrong here?
Thanks in advance!
let firstName = "Firstname"
let lastName = "Lastname"
let telephoneNumber = "1234567890"
let notes = "This is a note"
let person: ABRecordRef = ABPersonCreate().takeRetainedValue()
let couldSetFirstName = ABRecordSetValue(person, kABPersonFirstNameProperty, firstName as CFTypeRef, nil)
let couldSetLastName = ABRecordSetValue(person, kABPersonLastNameProperty, lastName as CFTypeRef, nil)
let couldSetPhoneNumber = ABRecordSetValue(person, kABPersonPhoneProperty, telephoneNumber as CFTypeRef, nil)
let couldSetNotes = ABRecordSetValue(person, kABPersonNoteProperty, notes, nil)
var error: Unmanaged<CFErrorRef>? = nil
let couldAddPerson = ABAddressBookAddRecord(inAddressBook, person, &error)
if couldAddPerson {
println("Added person")
} else{
println("Failed to add person")
return nil
}
if ABAddressBookHasUnsavedChanges(inAddressBook){
var error: Unmanaged<CFErrorRef>? = nil
let couldSaveAddressBook = ABAddressBookSave(inAddressBook, &error)
if couldSaveAddressBook{
println("Saved address book")
} else {
println("Failed to save address book")
}
if couldSetFirstName && couldSetLastName {
println("Succesfully set first and last name")
} else{
println("Failed to set first and last name")
}
}
return person
Upvotes: 3
Views: 3401
Reputation: 57168
You're passing a string to set the value of kABPersonPhoneProperty
, which is not correct. The phone number is not a string property; it's a multi-value property. You need to set it using something like the code from here: How to create contacts in address book in iPhone SDK? (which is Objective-C, but should be straightforward to translate.)
NSString *phone = @"0123456789"; // the phone number to add
//Phone number is a list of phone number, so create a multivalue
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(phoneNumberMultiValue, phone, kABPersonPhoneMobileLabel, NULL);
ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, &anError); // set the phone number property
Upvotes: 2