App is Not asking contact permission to access contact in iOS 9 - ios

I am using The Following code for getting iPhone Contacts but my App is not getting Permission For Allow Contacts in iOS 9 . I have found this code from stack and the other references are also same .
- (void)getPersonOutOfAddressBook
{
//1
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil) {
NSLog(#"Succesful.");
//2
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
//3
NSUInteger i = 0; for (i = 0; i < [allContacts count]; i++)
{
NSMutableDictionary *persiondict =[[NSMutableDictionary alloc]init] ;
// Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
//4
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson,
kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
// person.firstName = firstName;
// person.lastName = lastName;
// person.fullName = fullName;
[persiondict setValue:fullName forKey:#"fullName"] ;
//email
//5
ABMultiValueRef emails = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);
//6
NSUInteger j = 0;
for (j = 0; j < ABMultiValueGetCount(emails); j++) {
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
if (j == 0) {
// person.homeEmail = email;
[persiondict setValue:email forKey:#"email"] ;
// NSLog(#"person.homeEmail = %# ", person.homeEmail);
}
else if (j==1)
[persiondict setValue:email forKey:#"email"] ;
}
//7
[ArrUserOfContacts addObject:persiondict];
}
//8
CFRelease(addressBook);
} else {
//9
NSLog(#"Error reading Address Book");
}
}
I am unable to find problem here , How can user get an permission for access contacts . Any Suggestion Will be helpfull .

ABAddressBookRequestAccessWithCompletion is deprecated in iOS 9. Now you should use Contacts framework. This is an example in Objective C:
CNContactStore * contactStore = [CNContactStore new];
[contactStore requestAccessForEntityType:entityType completionHandler:^(BOOL granted, NSError * _Nullable error) {
if(granted){
//
}
}];
In Swift 3:
CNContactStore().requestAccess(for: .contacts, completionHandler: { granted, error in
if (granted){
//
}
})
This will only ask for permission if the user hasn't denied or approved permissions for contacts in your app. You can't ask for permissions that have already been denied by the user (At least now in iOS 10), what you can do is redirect the user to Settings.

You need request permissions using ABAddressBookRequestAccessWithCompletion()
ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
if (!granted){
NSLog(#"Just denied");
return;
}
NSLog(#"Just authorized");
});

If you want to check user given contacts permission or not and, if permission is not given then show alert to move user in settings to give permission.
Then use the following function checkContactsPermission as:
-(void)checkContactsPermission {
//Check permission status
switch (ABAddressBookGetAuthorizationStatus()) {
case kABAuthorizationStatusAuthorized:
// Already permission given
break;
case kABAuthorizationStatusDenied:{
// Permission not given so move user in settings page to app.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Alert!" message:#"his app requires access to your contacts." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* SettingsButton = [UIAlertAction actionWithTitle:#"Settings"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSURL * settingsURL = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"%#%#",UIApplicationOpenSettingsURLString,[[NSBundle mainBundle]bundleIdentifier]]];
if (settingsURL) {
[[UIApplication sharedApplication] openURL:settingsURL];
}
}];
UIAlertAction* DeniedButton = [UIAlertAction actionWithTitle:#"Denied"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
[alert addAction:SettingsButton];
[alert addAction:DeniedButton];
[self presentViewController:alert animated:YES completion:nil];
}
case kABAuthorizationStatusRestricted: {
// Permission not given so move user in settings page to app.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Alert!" message:#"his app requires access to your contacts." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* SettingsButton = [UIAlertAction actionWithTitle:#"Settings"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSURL * settingsURL = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"%#%#",UIApplicationOpenSettingsURLString,[[NSBundle mainBundle]bundleIdentifier]]];
if (settingsURL) {
[[UIApplication sharedApplication] openURL:settingsURL];
}
}];
UIAlertAction* DeniedButton = [UIAlertAction actionWithTitle:#"Denied"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
[alert addAction:SettingsButton];
[alert addAction:DeniedButton];
[self presentViewController:alert animated:YES completion:nil];
}
break;
case kABAuthorizationStatusNotDetermined:
// Permission not determin. so request for permission.
ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
if (granted){
// Already permission given
}
});
break;
}
}
for iOS 10 you can use Contacts framework for check permission.

Related

objective c How to refresh Access Token using Refresh Token

I am using Cognito user pool to authenticate users in my system. A successful authentication gives an ID Token (JWT), Access Token (JWT).Every one hour the  TokenExpiration . My question is once my Access Token expires, how do I use the stored refresh token to refresh my access token again?This is my code.
- (void)loginAWSMethod {
NSString *emailId = #"the email";
NSString *pwdTxt = #"the password";
NSLog(#"entered the login method %# %#",emailId,pwdTxt);
AWSCognitoIdentityUser *user = [pool getUser:emailId];
[[user getSession:emailId password:pwdTxt validationData:nil]
continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession *> * _Nonnull task)
{
if (task.error) {
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"ERROR CATCHED++++++");
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#"Incorrect email or password."
message:#""
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
}];
[alert addAction:yesButton];
[self presentViewController:alert animated:YES completion:nil];
});
[self removeWaitingProgress];
});
}else{
NSLog(#"the result is %#",task.result);
AWSCognitoIdentityUserSession *response1 = task.result;
token = response1.accessToken.tokenString;
NSLog(#"the token is %#",token);
[[user getDetails] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserGetDetailsResponse *> * _Nonnull task) {
AWSCognitoIdentityUserGetDetailsResponse *response = task.result;
for (AWSCognitoIdentityUserAttributeType *attribute in response.userAttributes) {
//print the user attributes
NSLog(#"Attribute: %# Value: %#", attribute.name, attribute.value);
if([attribute.name isEqualToString:#"sub"]){
cognitoID = attribute.value;
}
[defaults setValue:token forKey:#"token"];
[defaults setValue:#"yes" forKey:#"isLoggedIn"];
[defaults synchronize];
dispatch_async(dispatch_get_main_queue(), ^{
[self removeWaitingProgress];
[self gotoDashborad];
});
}
return nil;
}];
}
return nil;
}];
}
You should be able to simply invoke -[AWSCognitoIdentityUser getSession], which behind the scenes will either return the currently valid access token, or exchange the refresh token for new access token:
-(nullable NSString *)accessTokenStringForCurrentUser {
AWSCognitoIdentityUser *currentUser = [pool currentUser];
__block NSString *tokenString;
// `getSession` automatically exchanges the refresh token for a valid access token if needed
[[[currentUser getSession] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession *> * _Nonnull task) {
// (Error handling not shown)
if (task.result) {
AWSCognitoIdentityUserSessionToken *accessToken = task.result.accessToken;
tokenString = accessToken.tokenString;
}
return nil;
}] waitUntilFinished];
return tokenString;
}
You may also wish to look at the Cognito UserPools Sample app which has Objective C samples of using UserPools.

IOS Share Extension NSMutableArray addObject Unrecognized selector sent to instance

After clicking post to the share dialog, the Host App(e.g. Safari) hangs up if arrSites variable is currently not empty. I can only store 1 object inside my arrSites variable. How can I addObject to my NSMutableArray variable?
Below is my implemented code and it generates an error in [arrSites addObject:dictSite] line.
- (void)didSelectPost
{
inputItem = self.extensionContext.inputItems.firstObject;
NSItemProvider *urlItemProvider = [[inputItem.userInfo valueForKey:NSExtensionItemAttachmentsKey] objectAtIndex:0];
if ([urlItemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypeURL])
{
NSLog(#"++++++++++ Attachment is a URL");
[urlItemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error)
{
if (error)
{
NSLog(#"Error occured");
}
else
{
NSMutableArray *arrSites;
if ([sharedUserDefaults valueForKey:#"SharedExtension"]){
arrSites = [sharedUserDefaults objectForKey:#"SharedExtension"];
}else{
arrSites = [[NSMutableArray alloc] init];
}
NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, #"Text", url.absoluteString, #"URL",nil];
[arrSites addObject:dictSite];
[sharedUserDefaults setObject:arrSites forKey:#"SharedExtension"];
[sharedUserDefaults synchronize];
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Success"
message:#"V7 Posted Successfully."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[UIView animateWithDuration:0.20 animations:^
{
self.view.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height);
}
completion:^(BOOL finished)
{
[self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
}];
}];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
}
Without memory allocation you can't add the object to array, use like
// allocate the memory of array in before
NSMutableArray *arrSites = [[NSMutableArray alloc] init];
if ([sharedUserDefaults valueForKey:#"SharedExtension"]){
[arrSites addObjectsFromArray:[sharedUserDefaults objectForKey:#"SharedExtension"]];
}
[arrSites addObject:dictSite];
Most likely the source of the problem is that
arrSites = [sharedUserDefaults objectForKey:#"SharedExtension"];
creates immutable object (NSArray instead of NSMutableArray). You can fix this issue using
arrSites = [[sharedUserDefaults objectForKey:#"SharedExtension"] mutableCopy];
instead.

Integrate iCloud into ios App and Retrieve files from iCloud

I integrated iCloud into iOS app using raywenderlich https://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1
But iam unable to show all the files from iCloud to our iOS app and also need specific type of files like pdf, doc and docx
Can any one suggest me.
Follow below steps to integrate iCloud in iOS app and retrieve files.
1. Enable iCloud from your developer account.
2. Create iCloud containers entitlement at developer account.
3. Then just use below code where you want to integrate your iCloud integration.
First of all import #import and add iCloudDelegate delegate then set delegate:
// Setup iCloud
[[iCloud sharedCloud] setDelegate:self];
[[iCloud sharedCloud] setVerboseLogging:YES];
[[iCloud sharedCloud] setupiCloudDocumentSyncWithUbiquityContainer:nil];
[self showiCloudFiles];
then implementation of method showiCloudFiles below
-(void) showiCloudFiles{
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
else if ([[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == NO) {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"iCloud Disabled", #"You have disabled iCloud for this app. Would you like to turn it on again?");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
UIAlertAction* deleteButton = [UIAlertAction actionWithTitle:#"Turn On iCloud"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"userCloudPref"];
[[NSUserDefaults standardUserDefaults] synchronize];
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
}];
[alert addAction:deleteButton];
[self presentViewController:alert animated:YES completion:nil];
} else {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"Setup iCloud", #"iCloud is not available. Sign into an iCloud account on this device and check that this app has valid entitlements.");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
}];
[self presentViewController:alert animated:YES completion:nil];
}
}
After that for downloading file use UIDocumentPickerDelegate method:
#pragma mark - UIDocumentPickerDelegate
-(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
if (controller.documentPickerMode == UIDocumentPickerModeImport) {
//NSLog(#"%#",url);
[url startAccessingSecurityScopedResource];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent]; NSString *fileExtension = [newURL pathExtension]; if([fileExtension isEqualToString:#"zip"]) {if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"pages"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"numbers"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"key"] ) {
// Remove .zip if it is an iWork file
fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
}
NSError *fileConversionError;fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
// Do further code using fileData
}
}];
[url stopAccessingSecurityScopedResource];
}
}
For UIDocumentPicker visit this link iOS-8-UIDocumentPicker
Follow this guide
https://www.raywenderlich.com/12779/icloud-and-uidocument-beyond-the-basics-part-1
Download sample code at
https://github.com/rwenderlich/PhotoKeeper
Check if iCloud available
- (void)initializeiCloudAccessWithCompletion:(void (^)(BOOL available)) completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_iCloudRoot = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (_iCloudRoot != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud available at: %#", _iCloudRoot);
completion(TRUE);
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud not available");
completion(FALSE);
});
}
});
}
Query type of flies like pdf, doc and docx
- (NSMetadataQuery *)documentQuery {
NSMetadataQuery * query = [[NSMetadataQuery alloc] init];
if (query) {
// Search documents subdir only
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
// Add a predicate for finding the documents
NSString * filePattern = [NSString stringWithFormat:#"*.%#", PTK_EXTENSION];
[query setPredicate:[NSPredicate predicateWithFormat:#"%K LIKE %#",
NSMetadataItemFSNameKey, filePattern]];
}
return query;
}

Fetch only that phone contacts who are using the same app

I am developing an application in which I want to fetch contacts who are using the same application from my contact list in iphone.
How to do it? Any sample code or link ?
Please help me.
Note : I don't want to fetch all contacts in my ios application, I
just want to fetch the contacts who are using the same application.
import AddressBook framework first
Then call these two functions
-(void)AddressBookFetch{
ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
if (status == kABAuthorizationStatusDenied || status == kABAuthorizationStatusRestricted) {
// if you got here, user had previously denied/revoked permission for your
// app to access the contacts, and all you can do is handle this gracefully,
// perhaps telling the user that they have to go to settings to grant access
// to contacts
[[[UIAlertView alloc] initWithTitle:nil message:#"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone Settings app." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
return;
}
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (!addressBook) {
NSLog(#"ABAddressBookCreateWithOptions error: %#", CFBridgingRelease(error));
return;
}
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (error) {
NSLog(#"ABAddressBookRequestAccessWithCompletion error: %#", CFBridgingRelease(error));
}
if (granted) {
// if they gave you permission, then just carry on
[self listPeopleInAddressBook:addressBook];
} else {
// however, if they didn't give you permission, handle it gracefully, for example...
dispatch_async(dispatch_get_main_queue(), ^{
// BTW, this is not on the main thread, so dispatch UI updates back to the main queue
[[[UIAlertView alloc] initWithTitle:nil message:#"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone Settings app." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
});
}
CFRelease(addressBook);
});
}
Then list contact by this function
- (void)listPeopleInAddressBook:(ABAddressBookRef)addressBook
{
NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
numberOfPeople = [allPeople count];
for (NSInteger i = 0; i < numberOfPeople; i++) {
ABRecordRef person = (__bridge ABRecordRef)allPeople[i];
NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSLog(#"Name:%# %#", firstName, lastName);
if (firstName==nil) {
firstName=#"";
}
[nm addObject:firstName];
if (lastName==nil) {
lastName=#"";
}
[ttl addObject:lastName];
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
// CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
//for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
NSString *phoneNumber = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, 0));
NSLog(#" phone:%#", phoneNumber);
if (phoneNumber==nil) {
phoneNumber=#"";
}
[phn addObject:phoneNumber];
// }
// CFRelease(phoneNumbers);
NSLog(#"=============================================");
}
}
Its not possible without back-end, you can not do it within only ios application.

iOS 8 adding contact to address book

I'm trying to add a contact to the address book in iOS8. Unable to do so anymore. Here's my code below:
-(void)addPersonToAddressBook {
NSString * fullName = integrationDictionary[#"fullName"];
ABPeoplePickerNavigationController *pp =[ABPeoplePickerNavigationController new];
ABAddressBookRef addressBook = [pp addressBook];
ABRecordRef entry = ABPersonCreate();
CFErrorRef cfError=nil;
ABRecordSetValue(entry, kABPersonFirstNameProperty, (__bridge CFTypeRef)(fullName) , nil);
ABAddressBookAddRecord(addressBook, entry, &cfError);
if (ABAddressBookSave(addressBook, &cfError)) {
NSString *saveMessage = [NSString stringWithFormat:#"%# has been added to your address book.", fullName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Contact Added" message:saveMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
} else {
NSString *saveMessage = [NSString stringWithFormat:#"There was an error adding %# to your address book.", fullName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Uh Oh" message:saveMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
NSLog(#"error is %#", cfError);
The error is showing up as null. Has anyone seen this before? Any workarounds?
The error is returning NULL because there's no error registered.
The problem is that [pp addressBook] is returning nil. So your ABAddressBookRef addressBook reference is nil.
The workaround is to use ABAddressBookCreateWithOptions instead of [pp addressBook] method of ABPeoplePickerNavigationController.
Here's a sample which works just fine on both iOS 7.1 & iOS 8.1:
-(void)requestAuthorizationAndAddPersonToAddressBook
{
// Request authorization to Address Book
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access has been granted, add the contact
[self addPersonToAddressBook];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self addPersonToAddressBook];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}
}
-(void)addPersonToAddressBook {
NSString * fullName = #"James Bond";
CFErrorRef abCreateError = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &abCreateError);
if (abCreateError) {
NSLog(#"Error occurred: %#", abCreateError);
}
ABRecordRef entry = ABPersonCreate();
CFErrorRef cfError=nil;
ABRecordSetValue(entry, kABPersonFirstNameProperty, (__bridge CFTypeRef)(fullName) , nil);
ABAddressBookAddRecord(addressBook, entry, &cfError);
if (ABAddressBookSave(addressBook, &cfError)) {
NSString *saveMessage = [NSString stringWithFormat:#"%# has been added to your address book.", fullName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Contact Added" message:saveMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
} else {
NSString *saveMessage = [NSString stringWithFormat:#"There was an error adding %# to your address book.", fullName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Uh Oh" message:saveMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
if (cfError) {
NSLog(#"error is %#", cfError);
}
}

Resources