Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add contact to addressbook in iphone objective-c

What is the correct way to set street address etc in addressbook and let the user save it on iphone?

EDIT: removed the specific code-problem and made it more general

like image 830
hfossli Avatar asked Dec 04 '22 14:12

hfossli


1 Answers

This is a complete working sample of how to show an person by creating an ABRecordRef and pushing it into the view using an viewcontroller

///////////////////////////// Hook it up to a custom action.

-(IBAction)addToAddressbook:(id)sender{  
    ABUnknownPersonViewController *unknownPersonViewController = [[ABUnknownPersonViewController alloc] init];
    unknownPersonViewController.displayedPerson = (ABRecordRef)[self buildContactDetails];
    unknownPersonViewController.allowsAddingToAddressBook = YES;
    [self.navigationController pushViewController:unknownPersonViewController animated:YES];
    [unknownPersonViewController release]; 
}

//////////////////////////// This is the guy that builds the ABrecordRef

- (ABRecordRef)buildContactDetails {
    NSLog(@"building contact details");
    ABRecordRef person = ABPersonCreate(); 
    CFErrorRef  error = NULL;  

    // firstname
    ABRecordSetValue(person, kABPersonFirstNameProperty, @"Don Juan", NULL);

    // email
    ABMutableMultiValueRef email = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(email, @"[email protected]", CFSTR("email"), NULL);
    ABRecordSetValue(person, kABPersonEmailProperty, email, &error);
    CFRelease(email); 

    // Start of Address
    ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);  
    NSMutableDictionary *addressDict = [[NSMutableDictionary alloc] init];
    [addressDict setObject:@"The awesome road numba 1" forKey:(NSString *)kABPersonAddressStreetKey];   
    [addressDict setObject:@"0568" forKey:(NSString *)kABPersonAddressZIPKey];  
    [addressDict setObject:@"Oslo" forKey:(NSString *)kABPersonAddressCityKey]; 
    ABMultiValueAddValueAndLabel(address, addressDict, kABWorkLabel, NULL);
    ABRecordSetValue(person, kABPersonAddressProperty, address, &error); 
    [addressDict release];
    CFRelease(address); 
    // End of Address

    if (error != NULL) 
        NSLog(@"Error: %@", error);

    [(id)person autorelease];
    return person;
}

//////////////////////////// Wire up in the header:

Remember to import these frameworks:

#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h> 

Set the delegate

ABNewPersonViewControllerDelegate

And add this to the interface

ABNewPersonViewController *newPersonController;
like image 161
hfossli Avatar answered Dec 15 '22 11:12

hfossli