Fetch only that phone contacts who are using the same app - ios

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.

Related

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

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.

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

How to fetch contacts from AddressBook and store it in array in iOS 7?

I am trying to fetch contacts from address book and then to store it in an array.I am not able to do this.I checked various posts on stack overflow and i am writing the same code but not able to do?
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil) {
NSLog(#"Succesful.");
allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSLog(#"allContacts.count = %d",[allContacts count]);} allContact count is always zero
#property (nonatomic, assign) ABAddressBookRef addressBook;
// Check user permission
-(void)requestAddressBookAccess
{
ViewController * __weak weakSelf = self;
ABAddressBookRequestAccessWithCompletion(self.addressBook, ^(bool granted, CFErrorRef error)
{
if (granted)
{
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf accessGrantedForAddressBook];
});
}
else{
}
});
}
// Get all the contect
-(void)accessGrantedForAddressBook{
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFMutableArrayRef peopleMutable = CFArrayCreateMutableCopy(
kCFAllocatorDefault,
CFArrayGetCount(people),
people
);
NSMutableArray *allNames = (__bridge NSMutableArray*)peopleMutable;
}
That might be possible because you are not Requesting Access to Contacts from user.
Just add this to your code.
#import <AddressBookUI/AddressBookUI.h>
// Request authorization to Address Book
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
if (granted) {
// First time access has been granted, add the contact
[self _addContactToAddressBook];
} 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];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}

Link IOS Address Book to app

I want to link the address book view controller in my app , I have searched the internet and found in apple developer guide but they show how to open contacts picker when clicking on a button and I don't want that I want the contacts picker be a view controller in my storyboard . I think i can do that by making a custom tableviewcontroller and getting information from address book or can I do it directly ?
This should help you get started:
Also, don't forget to import and link to the following frameworks:
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
Simply call: [self requestPermissionForContacts];
- (void)requestPermissionForContacts
{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
{
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error)
{
if (granted)
{
dispatch_async(dispatch_get_main_queue(), ^
{
[self findContacts];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Find Contacts" message:#"To allow us to find your contacts, you will need to go to the Settings app > Privacy > Contacts, and set your app name here to On." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
});
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
{
[self findContacts];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Find Contacts" message:#"To allow us to find your contacts, you will need to go to the Settings app > Privacy > Contacts, and set your app name here to On." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
- (void)findContacts
{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
CFIndex numberOfPeople = CFArrayGetCount(people);
if (numberOfPeople > 0)
{
NSMutableArray *mutableEmailsArray = [[NSMutableArray alloc]init];
NSMutableArray *mutablePhonesArray = [[NSMutableArray alloc]init];
for (int i = 0; i < numberOfPeople; i++)
{
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
ABMultiValueRef emails = (__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonEmailProperty));
ABMultiValueRef phones = (__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));
if (ABMultiValueGetCount(emails) > 0)
{
[mutableEmailsArray addObjectsFromArray:((__bridge NSArray *)(ABMultiValueCopyArrayOfAllValues(emails)))];
}
if (ABMultiValueGetCount(phones) > 0)
{
[mutablePhonesArray addObjectsFromArray:((__bridge NSArray *)(ABMultiValueCopyArrayOfAllValues(phones)))];
}
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:#"%ld Emails %ld Phone Numbers", (unsigned long)mutableEmailsArray.count, (unsigned long)mutablePhonesArray.count] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"No Contacts" message:#"No contacts were found on your device." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}

Need suggestion to integrate gmail account in iOS developlment

I am new to iOS programming, and just want to do something fun.
I want to develop a mail client app for iPhone, it can add email accounts such as gmail and Yahoo and so on. I searched online for a while and also find some answers, before I dive into the details I just want someone who has similar experience give me some suggestions about which method is the best.
thanks
I have recently implemented gmail api to fetch gmail contacts and their email in my tableview. Gmail api is depricated, thats why you might have not got any proper documentation for that.
To implement gmail use libGDataTouchStaticLib.a library, with Gdata headers (search on google for that otherwise send me your email i will send you its zip).
The code to get gmail details are as follows
- (void)getGoogleContacts {
GDataServiceGoogleContact *service = [self contactService];
GDataServiceTicket *ticket;
BOOL shouldShowDeleted = TRUE;
// request a whole buncha contacts; our service object is set to
// follow next links as well in case there are more than 2000
const int kBuncha = 2000;
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
[query setShouldShowDeleted:shouldShowDeleted];
[query setMaxResults:kBuncha];
ticket = [service fetchFeedWithQuery:query
delegate:self
didFinishSelector:#selector(contactsFetchTicket:finishedWithFeed:error:)];
[self setContactFetchTicket:ticket];
}
- (void)setContactFetchTicket:(GDataServiceTicket *)ticket {
mContactFetchTicket = ticket;
}
- (GDataServiceGoogleContact *)contactService {
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
// update the username/password each time the service is requested
NSString *username = [txtUserName text];
NSString *password = [txtPasswrod text];
[service setUserCredentialsWithUsername:username
password:password];
return service;
}
// contacts fetched callback
- (void)contactsFetchTicket:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedContact *)feed
error:(NSError *)error {
if (error) {
NSDictionary *userInfo = [error userInfo];
NSLog(#"Contacts Fetch error :%#", [userInfo objectForKey:#"Error"]);
if ([[userInfo objectForKey:#"Error"] isEqual:#"BadAuthentication"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Authentication Failed"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Failed to get Contacts."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
} else {
NSArray *contacts = [feed entries];
NSLog(#"Contacts Count: %d ", [contacts count]);
[mutAryGoogleContacts removeAllObjects];
for (int i = 0; i < [contacts count]; i++) {
NSMutableDictionary *aDictContactDetails=[NSMutableDictionary dictionary];
GDataEntryContact *contact = [contacts objectAtIndex:i];
// Email
GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
NSString* ContactEmail = [email address];
if (ContactEmail) {
[aDictContactDetails setObject:ContactEmail forKey:#"email"];
// Name
NSString *ContactName = [[[contact name] fullName] contentStringValue];
if (ContactName) {
[aDictContactDetails setObject:ContactName forKey:#"friendName"];
}
[mutAryGoogleContacts addObject:aDictContactDetails];
}
}
//Push to next vc or do whatever you want
}
}

Resources