在ios地址簿中添加联系人

时间:2013-05-24 06:19:14

标签: iphone ios objective-c ipad

我想在我的地址簿中添加联系人。我正在开发一个应用程序,我已经通过了很多链接,我有以下代码,但现在我被卡住了。

我已导入:

    #import <AddressBook/AddressBook.h>
    #import <AddressBookUI/AddressBookUI.h
viewcontroller.m中的

-(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];
}

- (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, @"expert.in@computer.com", 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;
}

UI我有一个IBAction按钮连接到addToAddressbook,但点击后,没有任何事情发生 - 所以我需要做什么才能在UI或在代码?

1 个答案:

答案 0 :(得分:0)

查看代码后,我发现您错过了ABAddressBookSave语句。设置

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

// email
ABRecordSetValue(person, kABPersonEmailProperty, email, &error);

// Address
ABRecordSetValue(person, kABPersonAddressProperty, address, &error);

您应该拨打ABAddressBookSave,如下所示。

ABAddressBookSave(ABAddressBookRef addressBook, CFErrorRef* error);