Multi value url addressbook iphone - iphone

I want to create a new contact in the addressbook.
The problem appears when you want to store more URLs (web addresses to some social networks).
My code works perfectly in simulator of iOS6. But in real iPhone with iOS6, stores all values ​​except the urls.
I've been looking for a few days and can not find a solution, I will be very grateful if anyone can help.
My code:
-(void) addContactToAddressBook:(ABAddressBookRef) iPhoneAddressBook
{
CFErrorRef error = NULL;
ABRecordRef newPerson = ABPersonCreate();
//Name and phone number
ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFStringRef)_nameField.text, &error);
ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFStringRef)_phoneField.text, kABPersonPhoneMainLabel, NULL);
ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
//Email value
ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef)_emailField.text, kABWorkLabel, NULL);
ABRecordSetValue(newPerson, kABPersonEmailProperty, emailMultiValue, nil);
CFRelease(emailMultiValue);
//URL values
ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef)_FacebookField.text, (CFStringRef)#"Facebook", NULL);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef)_twitterField.text, (CFStringRef)#"Twitter", NULL);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef)_linkedinField.text, (CFStringRef)#"Linkedin", NULL);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef)_googleField.text, (CFStringRef)#"Google+", NULL);
ABRecordSetValue(newPerson, kABPersonURLProperty, urlMultiValue, nil);
CFRelease(urlMultiValue);
ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
ABAddressBookSave(iPhoneAddressBook, &error);
if (error != NULL)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Contact not saved" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Contact saved" message:#"Your contact was successfully saved" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
Thanks!

As per the documentation on apple's site (scroll down to Privacy in the middle of the page), access to the address book must be granted before it can be access programmatically. Here is what I ended up doing.
-(void)requestPermission
{
ABAddressBookRef iPhoneAddressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(iPhoneAddressBook, ^(bool granted, CFErrorRef error) {
if (granted) {
// First time access has been granted, add the contact
[self addContactToAddressBook:iPhoneAddressBook];
} else {
// User denied access
// Display an alert telling user the contact could not be added
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self addContactToAddressBook:iPhoneAddressBook];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}
}
-(void)addContactToAddressBook:(ABAddressBookRef)iPhoneAddressBook
{
CFErrorRef error = NULL;
ABRecordRef newPerson = ABPersonCreate();
//Name and phone number
ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFStringRef)_nameField.text, &error);
ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFStringRef)_phoneField.text, kABPersonPhoneMainLabel, NULL);
ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
CFRelease(multiPhone);
//Email value
ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef)_emailField.text, kABWorkLabel, NULL);
ABRecordSetValue(newPerson, kABPersonEmailProperty, emailMultiValue, nil);
CFRelease(emailMultiValue);
//URL values
ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef)_FacebookField.text, (CFStringRef)#"Facebook", NULL);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef)_twitterField.text, (CFStringRef)#"Twitter", NULL);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef)_linkedinField.text, (CFStringRef)#"Linkedin", NULL);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef)_googleField.text, (CFStringRef)#"Google+", NULL);
ABRecordSetValue(newPerson, kABPersonURLProperty, urlMultiValue, nil);
CFRelease(urlMultiValue);
// ...
// Set other properties
// ...
ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
ABAddressBookSave(iPhoneAddressBook, &error);
CFRelease(newPerson);
CFRelease(iPhoneAddressBook);
if (error != NULL)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Contact not saved" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Contact saved" message:#"Your contact was successfully saved" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}

Related

my contact not add in addressbook in ios 7

I am a beginner in iOS development; this code is working in iOS 6 but does not work in iOS 7 ...
My code is below, I want to add contacts into my address book. I am developing an app where I have gone through many links, and I have following code, but now I am stuck...
I have imported:
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
ViewController.m file
ABAddressBookRef ab = ABAddressBookCreate();
// To add a new ab entry with telephone number
ABRecordRef newPerson = ABPersonCreate();
ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFStringRef) nameFirststr, nil);
ABRecordSetValue(newPerson, kABPersonLastNameProperty, (__bridge CFStringRef)#"Jones", nil);
//phone
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(phoneNumberMultiValue ,(__bridge CFStringRef)myphone,kABPersonPhoneMobileLabel, NULL);
ABRecordSetValue(newPerson, kABPersonPhoneProperty, phoneNumberMultiValue, nil);
// Adreess
ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
if (Address)
{
if (Address)
addressDictionary[(NSString *) kABPersonAddressStreetKey] = [NSString stringWithFormat:#"%#\n%#", Address, Address];
else
addressDictionary[(NSString *) kABPersonAddressStreetKey] = Address;
// if (true)
// addressDictionary[(NSString *)kABPersonAddressCityKey] = #"city";
// if (true)
// addressDictionary[(NSString *)kABPersonAddressStateKey] = #"city";
// if (true)
// addressDictionary[(NSString *)kABPersonAddressZIPKey] = #"city";
// if (true)
// addressDictionary[(NSString *)kABPersonAddressCountryKey] = #"city";
}
ABMultiValueAddValueAndLabel(multiAddress, (__bridge CFDictionaryRef) addressDictionary, kABWorkLabel, NULL);
ABRecordSetValue(newPerson, kABPersonAddressProperty, multiAddress, nil);
// email
if (emailstr)
{
ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef) emailstr, kABWorkLabel, NULL);
ABRecordSetValue(newPerson, kABPersonEmailProperty, emailMultiValue, nil);
}
if (Organization)
{
ABRecordSetValue(newPerson, kABPersonOrganizationProperty, (__bridge CFStringRef)Organization, nil);
}
if (title)
{
ABRecordSetValue(newPerson, kABPersonJobTitleProperty, (__bridge CFStringRef)title, nil);
}
if (notes)
{
ABRecordSetValue(newPerson, kABPersonNoteProperty, (__bridge CFStringRef)notes, nil);
}
if (webUrl)
{
ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef) webUrl, kABPersonHomePageLabel, NULL);
ABRecordSetValue(newPerson, kABPersonURLProperty, urlMultiValue, nil);
}
ABAddressBookAddRecord(ab, newPerson, nil);
ABAddressBookSave(ab,NULL);
if (ABAddressBookSave(ab, nil)) {
NSLog(#"\nPerson Saved successfuly");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Your contact sucessfully Add" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
} else {
NSLog(#"\n Error Saving person to AddressBook");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Error...!!!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
}
check if addressbook is allowed
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access has been granted, add the contact
[self addContact];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self addContact];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Access Denied" message:#"Please give access to AddressBook via settings." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}
also replace first line
CFErrorRef * error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
try this code...
ABPeoplePickerNavigationController *peoplePicker=[[ABPeoplePickerNavigationController alloc] init];
ABAddressBookRef addressBook = [peoplePicker addressBook];
// create person record
ABRecordRef person = ABPersonCreate();
// set name and other string values
UIImage *personImage = [UIImage imageNamed:#"cinema.png"];
NSData *dataRef = UIImagePNGRepresentation(personImage);
NSString *firstName=#"Raj";
NSString *lastName=#"Patel";
NSString *organization=#"Ilesh Pvt Ltd.";
NSString *jobTitle=#"iPhone App Developer";
NSString *departMent=#"Mobile Division";
NSString *webURL=#"http://www.google.com";
NSString *personEmail=#"goel.anjan#gmail.com";
NSString *phoneNo=#"913654985 or 76876879 or 845676764";
NSString *personNote=#"I am just a kid";
NSString *addressOne=#"Ahmedabad";
NSString *addressTwo=#"Ahmedabad";
NSString *cityName=#"Ahmedabad";
NSString *stateName=#"Gujarat";
NSString *pinCode=#"38008";
NSString *country=#"India";
CFErrorRef cfError=nil;
ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFStringRef)organization, NULL);
if (firstName) {
ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridge CFTypeRef)(firstName) , nil);
}
if (lastName) {
ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFTypeRef)(lastName) , nil);
}
if (jobTitle) {
ABRecordSetValue(person, kABPersonJobTitleProperty,(__bridge CFTypeRef)(jobTitle), nil);
}
if (departMent) {
ABRecordSetValue(person, kABPersonDepartmentProperty,(__bridge CFTypeRef)(departMent), nil);
}
if (personNote) {
ABRecordSetValue(person, kABPersonNoteProperty, (__bridge CFTypeRef)(personNote), nil);
}
if (dataRef) {
ABPersonSetImageData(person, (__bridge CFDataRef)dataRef,&cfError);
}
if (webURL)
{
ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef) webURL, kABPersonHomePageLabel, NULL);
ABRecordSetValue(person, kABPersonURLProperty, urlMultiValue, nil);
CFRelease(urlMultiValue);
}
if (personEmail)
{
ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef) personEmail, kABWorkLabel, NULL);
ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, nil);
CFRelease(emailMultiValue);
}
if (phoneNo)
{
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
NSArray *venuePhoneNumbers = [phoneNo 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 (addressOne)
{
if (addressTwo)
addressDictionary[(NSString *) kABPersonAddressStreetKey] = [NSString stringWithFormat:#"%#\n%#", addressOne, addressTwo];
else
addressDictionary[(NSString *) kABPersonAddressStreetKey] = addressOne;
}
if (cityName)
addressDictionary[(NSString *)kABPersonAddressCityKey] = cityName;
if (stateName)
addressDictionary[(NSString *)kABPersonAddressStateKey] = stateName;
if (pinCode)
addressDictionary[(NSString *)kABPersonAddressZIPKey] = pinCode;
if (country)
addressDictionary[(NSString *)kABPersonAddressCountryKey] = country;
ABMultiValueAddValueAndLabel(multiAddress, (__bridge CFDictionaryRef) addressDictionary, kABWorkLabel, NULL);
ABRecordSetValue(person, kABPersonAddressProperty, multiAddress, NULL);
CFRelease(multiAddress);
//Add person Object to addressbook Object.
ABAddressBookAddRecord(addressBook, person, &cfError);
if (ABAddressBookSave(addressBook, nil)) {
NSLog(#"\nPerson Saved successfuly");
} else {
NSLog(#"\n Error Saving person to AddressBook");
}
modified code:
CFErrorRef * error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access has been granted, add the contact
[self addContact];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self addContact];
}
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access has been granted, add the contact
[self addContact];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self addContact];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Access Denied" message:#"Please give access to AddressBook via settings." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}

AddressBook Issue While adding more then 500 contacts

I am working on an iphone application that crashes where a user has a lot of contacts.Below is a function call that causes a crash, but only when a user has approx. more than 500 contacts.Below is a function call.Thanks in advance.
- (IBAction)addToAddressBook{
NSString *importString = [[NSString alloc] init];
importString = importTextView.text;
if (importString==nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Could not Find Text"
message:#"Try Pasting the Text Again"
delegate:nil
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert show];
[alert release];
}
statusLabel.text = #"Importing Lines";
NSArray *importLines = [importString componentsSeparatedByString:#"\n"];
[importString release];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFRetain(addressBook);
ABRecordRef person;
CFErrorRef error = NULL;
ABMutableMultiValueRef multiPhone;
ABMutableMultiValueRef multiURL = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
ABMutableMultiValueRef multiDate = ABMultiValueCreateMutable(kABMultiStringPropertyType);
NSMutableDictionary *addressDictionary;
statusLabel.text = #"Counting Records";
int totalRecords = 0;
for( int j = 0; j < 5; j++){
NSString *line = [importLines objectAtIndex:j];
if ([line rangeOfString: #"Contacts:"].location!=NSNotFound) {
NSString *totalContactsLabel = [[line componentsSeparatedByString:#" Contacts: "] objectAtIndex:1];
totalRecords = [totalContactsLabel intValue];
}
}
int recordNumber = 0;
statusLabel.text = [NSString stringWithFormat:#"%i/%i", recordNumber, totalRecords];
for (NSString *line in importLines)
{
if (![line isEqualToString:#""])
{
NSMutableString *mutableLine = [NSMutableString stringWithString: line];
if ([line hasPrefix:#"---"]) {
//NSLog(#"starting new person");
person = ABPersonCreate();
multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType); //clear multiphone for each new person
multiURL = ABMultiValueCreateMutable(kABMultiStringPropertyType);
multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
multiDate = ABMultiValueCreateMutable(kABMultiStringPropertyType);
multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
} else if ([line hasPrefix:#"First Name: "]) {
[mutableLine deleteCharactersInRange: [mutableLine rangeOfString: #"First Name: "]];
line = (NSString *)mutableLine;
ABRecordSetValue(person, kABPersonFirstNameProperty, line, &error);
} else if ([line hasPrefix:#"Middle Name: "]) {
[mutableLine deleteCharactersInRange: [mutableLine rangeOfString: #"Middle Name: "]];
line = (NSString *)mutableLine;
ABRecordSetValue(person, kABPersonMiddleNameProperty, line, &error);
} else if ([line hasPrefix:#"Last Name: "]) {
[mutableLine deleteCharactersInRange: [mutableLine rangeOfString: #"Last Name: "]];
line = (NSString *)mutableLine;
ABRecordSetValue(person, kABPersonLastNameProperty, line, &error);
} else if ([line rangeOfString: #"Phone:"].location!=NSNotFound) {
NSString *phoneLabel = [[line componentsSeparatedByString:#" Phone: "] objectAtIndex:0];
NSString *phoneContent = [[line componentsSeparatedByString:#" Phone: "] objectAtIndex:1];
if ([phoneLabel isEqualToString:#"Mobile"]) {
ABMultiValueAddValueAndLabel(multiPhone, phoneContent, kABPersonPhoneMobileLabel, NULL);
ABRecordSetValue(person, kABPersonPhoneProperty, multiPhone, &error);
} else if ([phoneLabel isEqualToString:#"Home"]) {
ABMultiValueAddValueAndLabel(multiPhone, phoneContent, kABHomeLabel, NULL);
ABRecordSetValue(person, kABPersonPhoneProperty, multiPhone, &error);
} else if ([phoneLabel isEqualToString:#"Work"]) {
ABMultiValueAddValueAndLabel(multiPhone, phoneContent, kABWorkLabel, NULL);
ABRecordSetValue(person, kABPersonPhoneProperty, multiPhone, &error);
} else if ([phoneLabel isEqualToString:#"iPhone"]) {
ABMultiValueAddValueAndLabel(multiPhone, phoneContent, kABPersonPhoneIPhoneLabel, NULL);
ABRecordSetValue(person, kABPersonPhoneProperty, multiPhone, &error);
} else {
ABMultiValueAddValueAndLabel(multiPhone, phoneContent, (CFStringRef)phoneLabel, NULL);
ABRecordSetValue(person, kABPersonPhoneProperty, multiPhone, &error);
}
}else if ([line rangeOfString: #"Email:"].location!=NSNotFound) {
NSString *emailLabel = [[line componentsSeparatedByString:#" Email: "] objectAtIndex:0];
NSString *emailContent = [[line componentsSeparatedByString:#" Email: "] objectAtIndex:1];
if ([emailLabel isEqualToString:#"Main"]) {
ABMultiValueAddValueAndLabel(multiEmail, emailContent, (CFStringRef)#"Main", NULL);
ABRecordSetValue(person, kABPersonEmailProperty, multiEmail, &error);
}else if ([emailLabel isEqualToString:#"Work"]) {
ABMultiValueAddValueAndLabel(multiEmail, emailContent, kABWorkLabel, NULL);
ABRecordSetValue(person, kABPersonEmailProperty, multiEmail, &error);
} else {
ABMultiValueAddValueAndLabel(multiEmail, emailContent, (CFStringRef)emailLabel, NULL);
ABRecordSetValue(person, kABPersonEmailProperty, multiEmail, &error);
}
}
if ([line hasPrefix:#"- -"]) {
//ABRecordSetValue(person, kABPersonEmailProperty, multiEmail, &error);
NSString *updateText;
NSString *firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
if (![self personAlreadyExists:firstName withName:lastName]){
ABAddressBookAddRecord(addressBook, person, &error);
ABAddressBookSave(addressBook, &error);
recordNumber++;
if (firstName==nil) {
updateText = [NSString stringWithFormat:#"%# added.", lastName];
} else if (lastName==nil) {
updateText = [NSString stringWithFormat:#"%# added.", firstName];
} else {
updateText = [NSString stringWithFormat:#"%# %# added.", firstName, lastName];
}
//NSLog(updateText);
} else {
if (firstName==nil) {
updateText = [NSString stringWithFormat:#"%# skipped.", lastName];
} else if (lastName==nil) {
updateText = [NSString stringWithFormat:#"%# skipped.", firstName];
} else {
updateText = [NSString stringWithFormat:#"%# %# skipped.", firstName, lastName];
}
//NSLog(updateText);
}
updateLabel.text = [updateLabel.text stringByAppendingFormat:#"%#\n", updateText];
statusLabel.text = #"";
NSLog(#"%i/%i Imported", recordNumber, totalRecords);
}
if (error != NULL) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Could not create contact" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
//[importLines release];
[activity stopAnimating];
activity.hidden = TRUE;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Add To Contacts" message:[NSString stringWithFormat:#"Contacts successfully restored!", ABRecordCopyValue(person, kABPersonFirstNameProperty)] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}

Address book implementation not working

I am using XCode 4.2 to develop a function to add a contact to the address book , here is my code
ABAddressBookRef *iPhoneAddressBook = ABAddressBookCreate();
ABRecordRef contact = ABPersonCreate();
//add infos
ABRecordSetValue(contact, kABPersonFirstNameProperty,(__bridge_retained CFStringRef)firstName, nil);
ABRecordSetValue(contact, kABPersonLastNameProperty,(__bridge_retained CFStringRef)lastName, nil);
ABRecordSetValue(contact, kABPersonOrganizationProperty, (__bridge_retained CFStringRef)organization, nil);
ABRecordSetValue(contact, kABPersonJobTitleProperty, (__bridge_retained CFStringRef)title, nil);
ABMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiRealPropertyType);
ABMultiValueAddValueAndLabel(multiPhone, (__bridge_retained CFStringRef)workTel, kABPersonPhoneMainLabel, NULL);
ABMultiValueAddValueAndLabel(multiPhone, (__bridge_retained CFStringRef)workFax, kABPersonPhoneWorkFAXLabel, NULL);
ABRecordSetValue(contact, kABPersonPhoneProperty, multiPhone, nil);
CFRelease(multiPhone);
ABMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiEmail, (__bridge_retained CFStringRef)email, kABWorkLabel, NULL);
ABRecordSetValue(contact, kABPersonEmailProperty, multiEmail, nil);
CFRelease(multiEmail);
// address
ABMultiValueRef multiAddress =ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
NSMutableDictionary *addressDict = [[NSMutableDictionary alloc]init];
[addressDict setObject:address forKey:(NSString *) kABPersonAddressStreetKey];
[addressDict setObject:city forKey:(NSString *) kABPersonAddressCityKey];
[addressDict setObject:province forKey:(NSString *) kABPersonAddressStateKey];
[addressDict setObject:postalCode forKey:(NSString *) kABPersonAddressZIPKey];
[addressDict setObject:address forKey:(NSString *) kABPersonAddressCountryKey];
ABMultiValueAddValueAndLabel(multiAddress, (__bridge_retained CFStringRef)addressDict, kABWorkLabel, NULL);
ABRecordSetValue(contact, kABPersonAddressProperty, multiAddress, NULL);
CFRelease(multiAddress);
ABMultiValueRef multiURL =ABMultiValueCreateMutable(kABMultiRealPropertyType);
ABMultiValueAddValueAndLabel(multiURL, (__bridge_retained CFStringRef)link, kABPersonURLProperty, NULL);
CFRelease(multiURL);
ABAddressBookAddRecord(iPhoneAddressBook, contact, nil);
BOOL didAdd = ABAddressBookSave(iPhoneAddressBook, nil);
CFRelease(contact);
CFRelease(iPhoneAddressBook);
//notifying the user that it was stored in his address book
if (didAdd) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirmation"
message:#"Contact Info successfully added to the Address Book"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
the program compiles and but it stops at this line :
ABMultiValueAddValueAndLabel(multiPhone, (__bridge_retained CFStringRef)workTel, kABPersonPhoneMainLabel, NULL);
I get this error (in green)
Thread 1
any clue ? what is wrong in the code ?
This is the definition of the function in which your error occurs:
bool ABMultiValueAddValueAndLabel (
ABMutableMultiValueRef multiValue,
CFTypeRef value,
CFStringRef label,
ABMultiValueIdentifier *outIdentifier
);
It appears you have switched the 2nd and 3rd arguments, right?

How to display a person record just after saving his data to iPhone Address Book?

this is my code and it works flawless, where my_value is a string with separator ','.
everythign works fin but i'd like to display the person record from the address book after i saved it, so in the function
if(isSaved) {
// **** code here ***
}
here the complete function
- (void) addToAgenda: (NSString*) my_value{
//NSArray *strings = [my_value componentsSeparatedByString: #","];
NSArray *dati=[[NSArray alloc] initWithArray:[my_value componentsSeparatedByString:#","]];
NSString *userwebsite = [dati objectAtIndex:0];
NSString *fname = [dati objectAtIndex:1];
NSString *lname = [dati objectAtIndex:2];
NSString *useremail = [dati objectAtIndex:3];;
NSString *usermobile = [dati objectAtIndex:4];
NSString *usercompany = #"xxx";
ABRecordRef aRecord = ABPersonCreate();
CFErrorRef anError = NULL;
// fisrst name
ABRecordSetValue(aRecord, kABPersonFirstNameProperty, fname, &anError);
// last name
ABRecordSetValue(aRecord, kABPersonLastNameProperty, lname, &anError);
// Phone Number.
ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multi, (CFStringRef)usermobile, kABWorkLabel, NULL);
ABRecordSetValue(aRecord, kABPersonPhoneProperty, multi, &anError);
CFRelease(multi);
// Company
ABRecordSetValue(aRecord, kABPersonDepartmentProperty, usercompany, &anError);
// email
NSLog(#"%#", useremail);
ABMutableMultiValueRef multiemail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiemail, (CFStringRef)useremail, kABWorkLabel, NULL);
ABRecordSetValue(aRecord, kABPersonEmailProperty, multiemail, &anError);
CFRelease(multiemail);
// website
NSLog(#"%#", userwebsite);
ABMutableMultiValueRef multiweb = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiweb, (CFStringRef)userwebsite, kABWorkLabel, NULL);
ABRecordSetValue(aRecord, kABPersonURLProperty, multiweb, &anError);
CFRelease(multiemail);
if (anError != NULL)
NSLog(#"error while creating..");
CFStringRef personname, personlname, personcompind, personemail, personwebsite, personcontact;
personname = ABRecordCopyValue(aRecord, kABPersonFirstNameProperty);
personlname = ABRecordCopyValue(aRecord, kABPersonLastNameProperty);
personcompind = ABRecordCopyValue(aRecord, kABPersonDepartmentProperty);
personemail = ABRecordCopyValue(aRecord, kABPersonEmailProperty);
personwebsite = ABRecordCopyValue(aRecord, kABPersonURLProperty);
personcontact = ABRecordCopyValue(aRecord, kABPersonPhoneProperty);
ABAddressBookRef addressBook;
CFErrorRef error = NULL;
addressBook = ABAddressBookCreate();
BOOL isAdded = ABAddressBookAddRecord (addressBook, aRecord, &error);
if(isAdded){
NSLog(#"added..");
}
if (error != NULL) {
NSLog(#"ABAddressBookAddRecord %#", error);
}
error = NULL;
BOOL isSaved = ABAddressBookSave (addressBook, &error);
if(isSaved) {
// **** code here ***
}
if (error != NULL) {
NSLog(#"ABAddressBookSave %#", error);
UIAlertView *alertOnChoose = [[UIAlertView alloc] initWithTitle:#"Unable to save this time" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alertOnChoose show];
[alertOnChoose release];
}
CFRelease(aRecord);
CFRelease(personname);
CFRelease(personlname);
CFRelease(personcompind);
CFRelease(personcontact);
CFRelease(personemail);
CFRelease(personwebsite);
CFRelease(addressBook);
}
You can use something like ABPersonViewController to display aRecord. Since it is a subclass of UIViewController, you can show it just like any other view controller, such as pushing it onto your navigation controller stack or presenting it modally.

How to add contact from within an iPhone app?

I am looking to keep track of people in my iPhone app - either adding them from existing contact data, or prompting the user to enter a new contact which will be saved to their Contacts.
I know I can create a persons record add write it to the Contact book, is it possible to display this screen?
Or do I have to implement my own view to facilitate creating a contact entry?
Apple provides ABNewPersonViewController. If you'd like some sample code, see Quick Contacts, in particular, this section:
ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
picker.newPersonViewDelegate = self;
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:picker];
[self presentModalViewController:navigation animated:YES];
[picker release];
[navigation release];
Have you tried using the ABNewPersonViewController?
See this and look for the section titled "Prompting the User to Create a New Person Record".
Below code can use for all IOS version,
#import ,#import
-(void)addContact
{
ABPeoplePickerNavigationController *peoplePicker;
ABAddressBookRef addressBook;
peoplePicker=[[ABPeoplePickerNavigationController alloc] init];
addressBook = [peoplePicker addressBook];
if(!IOS_OLDER_THAN_6)
{
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
{
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
if (granted)
{
if (![self checkExistsContacts]){
[self addThisContact];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App " message:#"Your contat is already exists." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App does not access to your contacts" message:#"To enable access go to : iPhone's Settings Privacy > Contacts > App > set 'On'" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
{
// The user has previously given access, add the contact
if (![self checkExistsContacts]){
[self addThisContact];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App " message:#"Your contat is already exists." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App does not access to your contacts" message:#"To enable access go to : iPhone's Settings Privacy > Contacts > App > set 'On'" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
if (![self checkExistsContacts]){
[SVProgressHUD showWithStatus:#"Saving..." maskType:SVProgressHUDMaskTypeClear];
NSString *strCell=#"1-800-123-1234”;
NSString *strFirstName=#“fname”;
NSString *strLastName=#“lname”;
NSUInteger addressbookId = 0;
ABRecordRef aRecord = ABPersonCreate();
CFErrorRef anError = NULL;
ABRecordSetValue(aRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)(strFirstName), &anError);
ABRecordSetValue(aRecord, kABPersonLastNameProperty, (__bridge CFTypeRef)(strLastName), &anError);
//(#"adding phonee");
ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
if(strCell) ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)(strCell), kABPersonPhoneIPhoneLabel,NULL);
CFRelease(multi);
ABAddressBookRef addressBook1;
CFErrorRef error = NULL;
addressBook1 = ABAddressBookCreate();
ABAddressBookAddRecord (addressBook1, aRecord, &error);
if (error != NULL) {
}
error = NULL;
if(ABAddressBookSave ( addressBook1, &error)){
addressbookId = ABRecordGetRecordID (aRecord);
}
if (error != NULL) {
}
CFRelease(aRecord);
CFRelease(addressBook1);
[SVProgressHUD dismiss];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App” message:#"Contact saved successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App " message:#"Your contat is already exists." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
}
- (void)addThisContact
{
[SVProgressHUD showWithStatus:#"Saving..." maskType:SVProgressHUDMaskTypeClear];
NSString *strCell=#"1-800-123-1234”;
NSString *strFirstName=#“fname”;
NSString *strLastName=#“lname”;
ABRecordRef person = ABPersonCreate();
// set name and other string values
CFErrorRef cfError=nil;
if (strFirstName) {
ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridge CFTypeRef)(strFirstName) , nil);
}
if (strLastName) {
ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFTypeRef)(strLastName) , nil);
}
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
if (strCell)
{
ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFTypeRef)(strCell), (CFStringRef)#"iPhone", NULL);
}
ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil);
CFRelease(phoneNumberMultiValue);
//Add person Object to addressbook Object.
ABAddressBookAddRecord(addressBook, person, &cfError);
if (ABAddressBookSave(addressBook, nil))
{
NSLog(#"\nPerson Saved successfuly");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App” message:#"Contact saved successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else
{
NSLog(#"\n Error Saving person to AddressBook");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“App” message:#"Contact details are not available." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
[SVProgressHUD dismiss];
}
- (BOOL)checkExistsContacts
{
NSString *strFirstName=#“fname”;
NSString *strLastName=#“lname”;
CFErrorRef err;
ABAddressBookRef adbk = ABAddressBookCreateWithOptions(addressBook,&err);
ABRecordRef moi = NULL;
CFArrayRef matts = ABAddressBookCopyPeopleWithName(adbk, (__bridge CFStringRef)strFirstName);
// might be multiple matts, but let's find the one with last name Neuburg
for (CFIndex ix = 0; ix < CFArrayGetCount(matts); ix++)
{
ABRecordRef matt = CFArrayGetValueAtIndex(matts, ix);
CFStringRef last = ABRecordCopyValue(matt, kABPersonLastNameProperty);
if (last && CFStringCompare(last, (CFStringRef)strLastName, 0) == 0)
moi = matt;
if (last)
CFRelease(last);
}
if (NULL == moi)
{
NSLog(#"Couldn't find myself");
CFRelease(matts);
CFRelease(adbk);
return NO;
}
else
{
NSLog(#"number already exists");
return YES;
}
return NO;
}