iphone - todos - iOS: ¿agregar contacto en Contactos?
porque no aparecen mis contactos en mi iphone (3)
Heyo! ¿Hay alguna forma de cómo, cuando un usuario toca un botón, puede agregar o actualizar un contacto en el Libro de contactos de Apple real? Algunos festivales tienen respuestas por correo electrónico que incluyen una "tarjeta de identificación" que el receptor puede descargar y encontrar en su libro de contactos.
Para presentar el controlador de contacto predeterminado
Paso 1: agrega ContactUi.framework al proyecto e importación
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
Paso 2: agrega este código
-(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];
}
Paso 3:
Para recibir una devolución de llamada cuando presiona HECHO o CANCELAR, agregue <CNContactViewControllerDelegate>
e implemente el método delegado.
- (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(nullable CNContact *)contact{
//You will get the callback here
}
Si hace esto en iOS 9 o posterior, debe usar el marco de Contacts
:
@import Contacts;
También necesita actualizar su Info.plist
, agregando un NSContactsUsageDescription
para explicar por qué su aplicación requiere acceso a los contactos.
Luego, cuando luego quiera agregar el contacto mediante programación, puede hacer algo como:
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);
}
}];
O, mejor aún, si desea agregar el contacto utilizando el marco ContactUI
(dando al usuario confirmación visual del contacto y dejar que lo personalicen como mejor le parezca), puede importar ambos marcos:
@import Contacts;
@import ContactsUI;
Y entonces:
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];
Mi respuesta original, utilizando los marcos de AddressBook
y AddressBookUI
para las versiones de iOS anteriores a la 9, está debajo. Pero si solo es compatible con iOS 9 y posterior, use los marcos de Contacts
y ContactsUI
como se describe anteriormente.
-
Si desea agregar un contacto a la libreta de direcciones del usuario, use AddressBook.Framework
para crear un contacto y luego use el AddressBookUI.Framework
para presentar la interfaz de usuario y permitir que el usuario la agregue a su libreta de direcciones personal utilizando ABUnknownPersonViewController
. Por lo tanto, puedes:
Agregue
AddressBook.Framework
yAddressBookUI.Framework
a su lista en Link Binary With Libraries ;Importar los archivos .h:
#import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h>
Escriba el código para crear un contacto, por ejemplo:
// 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);
Consulte la ABUnknownPersonViewController o la ABUnknownPersonViewController al usuario que ABUnknownPersonViewController un nuevo registro de persona de los datos existentes en la Guía de programación de la libreta de direcciones.
@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);
}
}];
}