Hi all,
this is a simple way to add programmatically a “Person” into your iphone contacts list.
First of all you need to include Address Book frameworks into your project:
#import AddressBook/AddressBook.h
#import AddressBookUI/AddressBookUI.h
After that, create an IBAction or something else and paste this function:
[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]- (IBAction) addToContacts {
ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
ABRecordRef newPerson = ABPersonCreate();
// add infos
ABRecordSetValue(newPerson, kABPersonFirstNameProperty, CFSTR("Alberto"), nil);
ABRecordSetValue(newPerson, kABPersonLastNameProperty, CFSTR("Pasca"), nil);
ABRecordSetValue(newPerson, kABPersonOrganizationProperty, CFSTR("albertopasca.it"), nil);
ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiPhone, @"328-1111111", kABHomeLabel, NULL);
ABMultiValueAddValueAndLabel(multiPhone,@"02-222222", kABWorkLabel, NULL);
ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
CFRelease(multiPhone);
ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiEmail, @"info@albertopasca.it", kABHomeLabel, NULL);
ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, nil);
// add an image !
UIImage *im = [UIImage imageNamed:@"logo_mobile_48.png"];
NSData *dataRef = UIImagePNGRepresentation(im);
ABPersonSetImageData(newPerson, (CFDataRef)dataRef, nil);
CFRelease(multiEmail);
ABAddressBookAddRecord(iPhoneAddressBook, newPerson, nil);
BOOL didAdd = ABAddressBookSave(iPhoneAddressBook, nil);
CFRelease(newPerson);
CFRelease(iPhoneAddressBook);
}[/code]
All the contact properties are hidden in kAB*******. Try it!
It’s all!!!
enjoy!
Rif: albertopasca.it