Thursday, June 4, 2009

Adding contact to Address Book using iPhone programming

The following is a sample code for adding a Contact to the iPhone Contact List using application.
Create a View Based Application using the X-Code, place a button with "Add Contact" label and link the addPicker action to the button and follow the below code

-(IBAction)addPicker:(id)sender {
   // Open the AddressBook of you iPhone using the ABAddressBookRef it does not create a new one rather it opens the existing Address book
   ABAddressBookRef addressBook= ABAddressBookCreate();
   // Create a Persons New Record
   ABRecordRef aRecord = ABPersonCreate();

   // Adding the FirstName, LastName, Company, Job Code
   ABRecordSetValue(aRecord, kABPersonFirstNameProperty, @"Your First Name",nil);
   ABRecordSetValue(aRecord, kABPersonLastNameProperty, @"Your Last Name", nil);
   ABRecordSetValue(aRecord, kABPersonOrganizationProperty, @"Your Company Name",nil);
   ABRecordSetValue(aRecord, kABPersonJobTitleProperty, @"Your Job Title",nil);

   // Adding the Phone details a person may have multiple phone numbers
   ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
   // Adding Phone number
   ABMultiValueAddValueAndLabel(multiPhone, @"1-555-555-5555", kABPersonPhoneMainLabel, NULL);
   // Adding a Custom property to the phone details property
   ABMultiValueAddValueAndLabel(multiPhone, @"1-444-444-4444", @"Clientphone", NULL);
   ABRecordSetValue(aRecord, kABPersonPhoneProperty, multiPhone,nil);
   CFRelease(multiPhone);

   // Adding the Email property
   ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
   ABMultiValueAddValueAndLabel(multiEmail, @"Your Email ID", kABWorkLabel, NULL);
   ABRecordSetValue(aRecord, kABPersonEmailProperty, multiEmail, nil);
   CFRelease(multiEmail);

   // Adding the Address property
   ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
   NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
   [addressDictionary setObject:@"Your Street Name" forKey:(NSString *) kABPersonAddressStreetKey];
   [addressDictionary setObject:@"Your City Name" forKey:(NSString *)kABPersonAddressCityKey];
   [addressDictionary setObject:@"Your State Name" forKey:(NSString *)kABPersonAddressStateKey];
   [addressDictionary setObject:@"ZIP Code" forKey:(NSString *)kABPersonAddressZIPKey];
   ABMultiValueAddValueAndLabel(multiAddress, addressDictionary, kABWorkLabel, NULL);
   ABRecordSetValue(aRecord, kABPersonAddressProperty, multiAddress,nil);
   CFRelease(multiAddress);

   // Finally adding the Person's record to the Address book and saving the Address book
   ABAddressBookAddRecord(addressBook, aRecord, nil);
   ABAddressBookSave(addressBook, nil);

  // Releasing the memory
  CFRelease(aRecord);
  CFRelease(addressBook);
}

No comments:

Post a Comment