iOS – 将联系人添加到联系人?

Heyo! 有没有办法如何当用户点击一个button,它可以添加或更新联系人到实际的苹果通讯录? 一些节日有电子邮件回复,包括一个“名片”,接收者可以下载并在他们的联系簿中find。

如果在iOS 9或更高版本中这样做,您应该使用Contacts框架:

 @import Contacts; 

您还需要更新您的Info.plist ,添加NSContactsUsageDescription来解释为什么您的应用程序需要访问联系人。

然后,当你想以编程的方式添加联系人时,你可以这样做:

 CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Access to contacts." message:@"This app requires access to contacts because ..." preferredStyle:UIAlertControllerStyleActionSheet]; [alert addAction:[UIAlertAction actionWithTitle:@"Go to Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil]; }]]; [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]]; [self presentViewController:alert animated:TRUE completion:nil]; return; } CNContactStore *store = [[CNContactStore alloc] init]; [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!granted) { dispatch_async(dispatch_get_main_queue(), ^{ // user didn't grant access; // so, again, tell user here why app needs permissions in order to do it's job; // this is dispatched to the main queue because this request could be running on background thread }); return; } // create contact CNMutableContact *contact = [[CNMutableContact alloc] init]; contact.familyName = @"Doe"; contact.givenName = @"John"; CNLabeledValue *homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:@"312-555-1212"]]; contact.phoneNumbers = @[homePhone]; CNSaveRequest *request = [[CNSaveRequest alloc] init]; [request addContact:contact toContainerWithIdentifier:nil]; // save it NSError *saveError; if (![store executeSaveRequest:request error:&saveError]) { NSLog(@"error = %@", saveError); } }]; 

或者,更好的是,如果您想使用ContactUI框架添加联系人(给予用户对联系人的可视确认并让他们按照他们认为合适的方式进行定制),则可以导入这两个框架:

 @import Contacts; @import ContactsUI; 

接着:

 CNContactStore *store = [[CNContactStore alloc] init]; // create contact CNMutableContact *contact = [[CNMutableContact alloc] init]; contact.familyName = @"Smith"; contact.givenName = @"Jane"; CNLabeledValue *homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:@"301-555-1212"]]; contact.phoneNumbers = @[homePhone]; CNContactViewController *controller = [CNContactViewController viewControllerForUnknownContact:contact]; controller.contactStore = store; controller.delegate = self; [self.navigationController pushViewController:controller animated:TRUE]; 

我原来的回答是,在9之前的iOS版本中使用AddressBookAddressBookUI框架如下。 但是,如果只支持iOS 9及更高版本,请使用上面概述的ContactsContactsUI框架。

如果要将联系人添加到用户的通讯簿中,请使用AddressBook.Framework创build联系人,然后使用AddressBookUI.Framework显示用户界面,以允许用户使用ABUnknownPersonViewController将其添加到其个人通讯簿中。 因此,您可以:

  1. AddressBook.FrameworkAddressBookUI.Framework添加到Link Binary With Libraries下的列表中;

  2. 导入.h文件:

     #import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h> 
  3. 编写代码来创build联系人,例如:

     // create person record ABRecordRef person = ABPersonCreate(); // set name and other string values ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFStringRef) venueName, NULL); if (venueUrl) { ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef) venueUrl, kABPersonHomePageLabel, NULL); ABRecordSetValue(person, kABPersonURLProperty, urlMultiValue, nil); CFRelease(urlMultiValue); } if (venueEmail) { ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef) venueEmail, kABWorkLabel, NULL); ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, nil); CFRelease(emailMultiValue); } if (venuePhone) { ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType); NSArray *venuePhoneNumbers = [venuePhone componentsSeparatedByString:@" or "]; for (NSString *venuePhoneNumberString in venuePhoneNumbers) ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFStringRef) venuePhoneNumberString, kABPersonPhoneMainLabel, NULL); ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil); CFRelease(phoneNumberMultiValue); } // add address ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init]; if (venueAddress1) { if (venueAddress2) addressDictionary[(NSString *) kABPersonAddressStreetKey] = [NSString stringWithFormat:@"%@\n%@", venueAddress1, venueAddress2]; else addressDictionary[(NSString *) kABPersonAddressStreetKey] = venueAddress1; } if (venueCity) addressDictionary[(NSString *)kABPersonAddressCityKey] = venueCity; if (venueState) addressDictionary[(NSString *)kABPersonAddressStateKey] = venueState; if (venueZip) addressDictionary[(NSString *)kABPersonAddressZIPKey] = venueZip; if (venueCountry) addressDictionary[(NSString *)kABPersonAddressCountryKey] = venueCountry; ABMultiValueAddValueAndLabel(multiAddress, (__bridge CFDictionaryRef) addressDictionary, kABWorkLabel, NULL); ABRecordSetValue(person, kABPersonAddressProperty, multiAddress, NULL); CFRelease(multiAddress); // let's show view controller ABUnknownPersonViewController *controller = [[ABUnknownPersonViewController alloc] init]; controller.displayedPerson = person; controller.allowsAddingToAddressBook = YES; // current view must have a navigation controller [self.navigationController pushViewController:controller animated:YES]; CFRelease(person); 

请参阅“ 地址簿编程指南”中的“ ABUnknownPersonViewController类引用”或“ 提示用户从现有数据创build新的个人logging”部分

显示默认联系人控制器

步骤1:将ContactUi.framework添加到项目并导入

  #import <Contacts/Contacts.h> #import <ContactsUI/ContactsUI.h> 

第二步:添加这个代码

  -(void)showAddContactController{ //Pass nil to show default contact adding screen CNContactViewController *addContactVC = [CNContactViewController viewControllerForNewContact:nil]; addContactVC.delegate=self; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addContactVC]; [viewController presentViewController:navController animated:NO completion:nil]; } 

第三步:

在按DONE或CANCEL时获取callback,添加<CNContactViewControllerDelegate>并实现委托方法。

 - (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(nullable CNContact *)contact{ //You will get the callback here } 
 @import Contacts; -(void)addToContactList { CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can add the desired contact" preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]]; [self presentViewController:alert animated:TRUE completion:nil]; return; } CNContactStore *store = [[CNContactStore alloc] init]; [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!granted) { dispatch_async(dispatch_get_main_queue(), ^{ // user didn't grant access; // so, again, tell user here why app needs permissions in order to do it's job; // this is dispatched to the main queue because this request could be running on background thread }); return; } // create contact CNMutableContact *contact = [[CNMutableContact alloc] init]; contact.givenName = @"Test"; contact.familyName = @"User"; CNLabeledValue *homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:@"91012-555-1212"]]; contact.phoneNumbers = @[homePhone]; CNSaveRequest *request = [[CNSaveRequest alloc] init]; [request addContact:contact toContainerWithIdentifier:nil]; // save it NSError *saveError; if (![store executeSaveRequest:request error:&saveError]) { NSLog(@"error = %@", saveError); } }]; }