iOS - 将联系人添加到联系人? [英] iOS - add contact into Contacts?

查看:200
本文介绍了iOS - 将联系人添加到联系人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Heyo!
有一种方式,当用户点击一个按钮,它可以添加或更新联系人到实际的苹果联系人书?一些节目有电子邮件回复,包括接收者可以在他们的联系人簿中下载并找到的名片。

解决方案

在iOS 9或更高版本中,您应该使用联系人框架:

  @import联系人

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



然后,当你想要以编程方式添加联系人,然后可以执行以下操作:

  CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; 
if(status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted){
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@访问联系人。消息:@此应用程序需要访问联系人,因为...preferredStyle:UIAlertControllerStyleActionSheet];
[alert addAction:[UIAlertAction actionWithTitle:@转到设置样式:UIAlertActionStyleDefault处理程序:^(UIAlertAction * _Nonnull action){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]选项: @ {} completionHandler:nil];
}]];
[alert addAction:[UIAlertAction actionWithTitle:@Cancelstyle:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:TRUE completion:nil];
return;
}

CNContactStore * store = [[CNContactStore alloc] init];

[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL grant,NSError * _Nullable error){
if(!approved){
dispatch_async(dispatch_get_main_queue(),^ {
//用户没有授予访问权限;
//所以,再次告诉用户这里为什么应用程序需要权限才能做到这一点;
//这被分派到主要的队列,因为这样请求可以在后台线程
}上运行);
return;
}

//创建联系人

CNMutableContact * contact = [[CNMutableContact alloc] init];
contact.familyName = @Doe;
contact.givenName = @John;

CNLabeledValue * homePhone = [CNLabeledValue taggedValueWithLabel:CNLabelHome值:[CNPhoneNumber phoneNumberWithStringValue:@312-555-1212]];
contact.phoneNumbers = @ [homePhone];

CNSaveRequest * request = [[CNSaveRequest alloc] init];
[request addContact:contact toContainerWithIdentifier:nil];

//保存

NSError * saveError;
if(![store executeSaveRequest:request error:& saveError]){
NSLog(@error =%@,saveError);
}
}];或者更好的是,如果你想使用 ContactUI添加联系人,那么你可以使用$ $ $ $ $ $ $ $ $ $ $ 框架(给用户可视化确认联系人,并让他们按照合适的方式进行裁剪),您可以导入两个框架:

  @import Contacts; 
@import ContactsUI;

然后:

 store $ [= CNContactStore alloc] init]; 

//创建联系人

CNMutableContact * contact = [[CNMutableContact alloc] init];
contact.familyName = @史密斯;
contact.givenName = @简;

CNLabeledValue * homePhone = [CNLabeledValue labeledValueWithLabel:CNLabelHome值:[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];

我的原始答案是使用 AddressBook AddressBookUI 框架在iOS 9之前的版本在下面。但是,如果仅支持iOS 9及更高版本,请使用上述联系人 ContactsUI 框架。



-



如果要向用户的通讯录添加联系人,请使用 AddressBook。框架创建联系人,然后使用 AddressBookUI.Framework 呈现用户界面,允许用户将其添加到他们的个人地址使用 ABUnknownPersonViewController 。因此,您可以:


  1. 添加 AddressBook.Framework AddressBookUI.Framework 到您的列表链接二进制与库;


  2. 导入.h文件:

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


  3. 编写代码以创建联系人,例如:

      //创建个人记录

    ABRecordRef person = ABPersonCreate();

    //设置名称和其他字符串值

    ABRecordSetValue(person,kABPersonOrganizationProperty,(__bridge CFStringRef)locationsName,NULL);

    if(venueUrl){
    ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(urlMultiValue,(__bridge CFStringRef)locationsUrl,kABPersonH​​omePageLabel,NULL);
    ABRecordSetValue(person,kABPersonURLProperty,urlMultiValue,nil);
    CFRelease(urlMultiValue);
    }

    if(placesEmail){
    ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(emailMultiValue,(__bridge CFStringRef)locationsEmail,kABWorkLabel,NULL);
    ABRecordSetValue(person,kABPersonEmailProperty,emailMultiValue,nil);
    CFRelease(emailMultiValue);
    }

    if(venuePhone){
    ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    NSArray *场所PhoneNumbers = [场所Phone ComponentsSeparatedByString:@或];
    for(NSString *场所PhoneNumberString在场所PhoneNumbers)
    ABMultiValueAddValueAndLabel(phoneNumberMultiValue,(__bridge CFStringRef)场所PhoneNumberString,kABPersonPhoneMainLabel,NULL);
    ABRecordSetValue(person,kABPersonPhoneProperty,phoneNumberMultiValue,nil);
    CFRelease(phoneNumberMultiValue);
    }

    //添加地址

    ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
    NSMutableDictionary * addressDictionary = [[NSMutableDictionary alloc] init];

    if(placesAddress1){
    if(venueAddress2)
    addressDictionary [(NSString *)kABPersonAddressStreetKey] = [NSString stringWithFormat:@%@ \%@,placesAddress1 ,会场地址2];
    else
    addressDictionary [(NSString *)kABPersonAddressStreetKey] = placesAddress1;
    }
    if(locationsCity)
    addressDictionary [(NSString *)kABPersonAddressCityKey] = locationsCity;
    if(placesState)
    addressDictionary [(NSString *)kABPersonAddressStateKey] = placesState;
    if(placesZip)
    addressDictionary [(NSString *)kABPersonAddressZIPKey] = placesZip;
    if(venueCountry)
    addressDictionary [(NSString *)kABPersonAddressCountryKey] = locationsCountry;

    ABMultiValueAddValueAndLabel(multiAddress,(__bridge CFDictionaryRef)addressDictionary,kABWorkLabel,NULL);
    ABRecordSetValue(person,kABPersonAddressProperty,multiAddress,NULL);
    CFRelease(multiAddress);

    //让我们看看控制器

    ABUnknownPersonViewController * controller = [[ABUnknownPersonViewController alloc] init];

    controller.displayedPerson = person;
    controller.allowsAddingToAddressBook = YES;

    //当前视图必须有一个导航控制器

    [self.navigationController pushViewController:controller animated:YES];

    CFRelease(person);


请参阅 ABUnknownPersonViewController类参考提示用户创建地址簿编程指南中的现有数据新记录部分。


Heyo! Is there a way how when a user taps a button it can add or update a contact into the actual Apple Contacts Book? Some festivals have email responses include a "name card" that the receiver can download and find in their contact book.

解决方案

If doing this in iOS 9 or later, you should use the Contacts framework:

@import Contacts;

You also need to update your Info.plist, adding a NSContactsUsageDescription to explain why your app requires access to contacts.

Then, when you then want to programmatically add the contact, then you can do something like:

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

Or, even better, if you want to add the contact using the ContactUI framework (giving the user visual confirmation of the contact and let them tailor it as they see fit), you can import both frameworks:

@import Contacts;
@import ContactsUI;

And then:

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

My original answer, using the AddressBook and AddressBookUI frameworks for iOS versions before 9, is below. But if only supporting iOS 9 and later, use the Contacts and ContactsUI frameworks as outlined above.

--

If you want to add a contact to the user's address book, you use AddressBook.Framework to create a contact, and then you use the AddressBookUI.Framework to present the user interface to allow the user to add it to their personal address book using ABUnknownPersonViewController. Thus, you can:

  1. Add AddressBook.Framework and AddressBookUI.Framework to your list under Link Binary With Libraries;

  2. Import the .h files:

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

  3. Write the code to create a contact, e.g.:

    // 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);
    

See the ABUnknownPersonViewController Class Reference or the Prompting the User to Create a New Person Record from Existing Data section of the Address Book Programming Guide.

这篇关于iOS - 将联系人添加到联系人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆