Possible ways to export IPhone addressbook db - iphone

I want to export IPhone's AddressBook.sqlitedb into my IPhone application.
I have searched around the net but everything seems to iterate over the "ABAddressBook"
but i want to know that is it possible to export IPhone's AddressBook.sqlitedb into my IPhone application programmatically?
Please let me know any valuable comments!!!
Thanks for your help.....

you have to fetch every single value and then insert it into your DB.
Here is the code through which i got iphone address book into my application's Db.
just call the below method where ever you want to get iphone Address Book but i'll suggest you to call this methos in delegat.m method- DidFinishLanching:
-(void)fetchRecordsFromAddressBook
{
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
//NSArray *addresses = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
//[arrayContacts removeAllObjects];
[self emptyDataContext];
for (int i = 0; i < nPeople; i++)
{
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);
////////////////// get first name ///////////////////
CFStringRef firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
CFStringRef lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
CFStringRef nickName = ABRecordCopyValue(ref, kABPersonNicknameProperty);
CFStringRef middleName = ABRecordCopyValue(ref, kABPersonMiddleNameProperty);
////////////////// get image ///////////////////
// ABMultiValueRef ContactImage = (ABMultiValueRef) ABRecordCopyValue(ref,kABPersonImageFormatThumbnail);
NSData *data=nil;
// NSLog(#"Image Testing is : %#",ref);
if(ABPersonHasImageData(ref))
{
data = [(NSData *) ABPersonCopyImageData(ref) autorelease];
if(data)
{
// NSLog(#"Im Testing is : %#",data);
//image = [[UIImage alloc] initWithData:data];
}
}
// NSLog(#"Im agte is : %#",ContactImage);
// NSLog(#" Name is : %#",firstName);
////////////////// get email ///////////////////
ABMultiValueRef emails = (ABMultiValueRef) ABRecordCopyValue(ref, kABPersonEmailProperty);
NSString *emailID=#"";
if(ABMultiValueGetCount(emails)>=1)
{
emailID = (NSString *)ABMultiValueCopyValueAtIndex(emails,0);
}
////////////////// get phone number ///////////////////
ABMultiValueRef phones = (ABMultiValueRef) ABRecordCopyValue(ref, kABPersonPhoneProperty);
NSString *phone=#"";
NSString *homeNumber = #"";
NSString *worknumber = #"";
if(ABMultiValueGetCount(phones)>=1)
{
//int ph = [ABMultiValueCopyValueAtIndex(phones, 0) intValue];
phone = (NSString *)ABMultiValueCopyValueAtIndex(phones,0);
}
// NSLog(#"%#",(NSString*)phone);
if(ABMultiValueGetCount(phones)>=2)
{
homeNumber = (NSString *)ABMultiValueCopyValueAtIndex(phones,1);
}
if(ABMultiValueGetCount(phones)>=3)
{
worknumber = (NSString *)ABMultiValueCopyValueAtIndex(phones,2);
}
NSMutableArray *arrayContacts = [[NSMutableArray alloc] init ];
///////////////////////////// insert into array ////////////////////////////
arrayContacts = [CoreDataAPIMethods getObjectsFromContext:#"AllContactData" :#"Index" :NO :self.managedObjectContext];
//////////////////////////// insert Index ///////////////////////////////
int NewEntryID;
if ([arrayContacts count] > 0)
{
AllContactData * Contacdata = [arrayContacts objectAtIndex:0];
NewEntryID = [Contacdata.Index intValue] +1;
}
else
{
NewEntryID = 1;
}
NSString *capitalisedSentence =
[(NSString *)firstName stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[(NSString *)firstName substringToIndex:1] capitalizedString]];
AllContactData *Contactitem=(AllContactData *)[NSEntityDescription insertNewObjectForEntityForName:#"AllContactData" inManagedObjectContext:self.managedObjectContext];
// NSLog(#"%#",capitalisedSentence);
Contactitem.Name = capitalisedSentence;
Contactitem.LastName = (NSString*)lastName;
Contactitem.NickName = (NSString*)nickName;
Contactitem.MiddleName = (NSString*)middleName;
Contactitem.Email=(NSString*)emailID;
phone = [phone stringByReplacingOccurrencesOfString:#"(" withString:#""];
phone = [phone stringByReplacingOccurrencesOfString:#")" withString:#""];
phone = [phone stringByReplacingOccurrencesOfString:#"+" withString:#""];
phone = [phone stringByReplacingOccurrencesOfString:#" " withString:#""];
phone = [phone stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSLog(#"The Replacing Stinr is : %#", phone);
Contactitem.PhoneNumber=(NSString*)phone;
Contactitem.HomeNumber=(NSString*)homeNumber;
Contactitem.WorkNumber=(NSString*)worknumber;
Contactitem.Index = [NSNumber numberWithInt:NewEntryID];
Contactitem.Image = data;
// NSLog(#"Image in databse is : %#",(NSData *)ContactImage);
if(firstName!=nil)
{
CFRelease(firstName);
}
CFRelease(ref);
}
CFRelease(allPeople);
///////////////////////////// save entries ////////////////////////////
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error...
}
}
-(void)emptyDataContext
{
self.managedObjectContext = [(Dial_Up_AppAppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext];
NSLog(#"managedObjectContext=%#",self.managedObjectContext);
// Get all counties, It's the top level object and the reference cascade deletion downward
NSMutableArray* mutableFetchResults = [CoreDataAPIMethods getObjectsFromContext:#"AllContactData" :#"Name" :YES :self.managedObjectContext];
// Delete all Counties
for (int i = 0; i < [mutableFetchResults count]; i++) {
[managedObjectContext deleteObject:[mutableFetchResults objectAtIndex:i]];
}
//[mutableFetchResults release];
// Update the data model effectivly removing the objects we removed above.
NSError *error;
if([mutableFetchResults count] > 0)
{
if (![managedObjectContext save:&error]) {
// Handle the error.
//NSLog([error domain]);
}
}
}
Hope this will help you.

Related

How to give permission to access phone Addressbook in ios 10.0?

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSContactsUsageDescription key with a string value explaining to the user how the app uses this data.
I added to the .plist NSContactsUsageDescription
doesn't work - device version:10.0
KTSContactsManager *addressBookManager = [KTSContactsManager sharedManager];
addressBookManager.delegate = self;
addressBookManager.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"firstName" ascending:YES]];
if ([isAddressBookTaken isEqualToString:#"false"]) {
[addressBookManager importContacts:^(NSArray *contacts) {
[EBLogger logWithTag:#"TBLContactManager" withBody:#"importContacts"];
DLPhoneBook *phoneBook = [DLPhoneBook new];
NSMutableArray *mutableArray = [NSMutableArray new];
for (int i = 0; i < contacts.count; ++i) {
NSDictionary *record = [contacts objectAtIndex:i];
NSError *err = nil;
DLContactRecord *contactRecord = [[DLContactRecord alloc] initWithDictionary:record error:&err];
NSLog(#" %# %# %# '",contactRecord.firstName, contactRecord.lastName, contactRecord.id);
}
}
You have to add information list in your plist,
Here is information plist for various privacy.
Add Privacy that you want in you plist and check again.
and ADD this code in your file,
- (void)viewDidLoad {
[super viewDidLoad];
contactList=[[NSMutableArray alloc] init];
ABAddressBookRef m_addressbook = ABAddressBookCreate();
if (!m_addressbook) {
NSLog(#"opening address book");
}
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(m_addressbook);
CFIndex nPeople = ABAddressBookGetPersonCount(m_addressbook);
for (int i=0;i < nPeople;i++) {
NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
//For username and surname
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFStringRef firstName, lastName;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
[dOfPerson setObject:[NSString stringWithFormat:#"%# %#", firstName, lastName] forKey:#"name"];
//For Email ids
ABMutableMultiValueRef eMail = ABRecordCopyValue(ref, kABPersonEmailProperty);
if(ABMultiValueGetCount(eMail) > 0) {
[dOfPerson setObject:(NSString *)ABMultiValueCopyValueAtIndex(eMail, 0) forKey:#"email"];
}
//For Phone number
NSString* mobileLabel;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++) {
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
[dOfPerson setObject:(NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:#"Phone"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
[dOfPerson setObject:(NSString*)ABMultiValueCopyValueAtIndex(phones, i) forKey:#"Phone"];
break ;
}
[contactList addObject:dOfPerson];
CFRelease(ref);
CFRelease(firstName);
CFRelease(lastName);
}
NSLog(#"array is %#",contactList);
}
}
For more about it visit,
http://sugartin.info/2011/09/07/get-information-from-iphone-address-book-in-contacts/
Hope it will help you.

ABAddressBook - How to find if a particular contact is modified or deleted from iPhone's address book?

I am working on a chat app. For which i need to save contacts. So i am saving all contacts from ABAddressBook in my core data entity. Problem is how can i know if a contact is modified or removed from iPhone's AddressBook? So that i will modify or remove that contact from my Core data entity.
if ABRecordGetRecordID(person) can be used as unique key or not
Given belew is code of adding contacts in core data.
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, nil);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople( addressBookRef );
CFIndex nPeople = ABAddressBookGetPersonCount( addressBookRef );
for ( int i = 0; i < nPeople; i++ )
{
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
}
NSString* firstName = (__bridge_transfer NSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);
if ([firstName hasPrefix:#"Protected by True"])
{
continue;
}
else if([firstName hasPrefix:#"Identified As Spam"])
{
continue;
}
NSString* lastName = (__bridge_transfer NSString*)ABRecordCopyValue(person,kABPersonLastNameProperty);
NSString *userEmail = nil;
ABMultiValueRef emailData = ABRecordCopyValue(person, kABPersonEmailProperty);
if(ABMultiValueGetCount(emailData) > 0) {
NSLog(#"email is:%#",(__bridge NSString *)ABMultiValueCopyValueAtIndex(emailData, 0));
userEmail = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emailData, 0);
}
NSString* phone = nil;
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person,kABPersonPhoneProperty);
if (ABMultiValueGetCount(phoneNumbers) > 0)
{
for (int i=0; i<ABMultiValueGetCount(phoneNumbers); i++)
{
phone = (__bridge_transfer NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, i);
NSString *asciiCharacters = #"0123456789";
NSCharacterSet *nonAsciiCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:asciiCharacters] invertedSet];
NSString *stringPhone = [[phone componentsSeparatedByCharactersInSet:nonAsciiCharacterSet] componentsJoinedByString: #""];
NSString *str = stringPhone;
stringPhone = [str stringByReplacingOccurrencesOfString:#"^0+"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, str.length)];
NSLog(#"modified %#", stringPhone);
NSString *phoneLabelLocalized;
CFStringRef labelStingRef = ABMultiValueCopyLabelAtIndex (phoneNumbers, i);
phoneLabelLocalized = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(labelStingRef);
if ([[PersistentStore getMyJID] rangeOfString:stringPhone].location != NSNotFound)
{
NSLog(#"my phone %#",stringPhone);
continue;
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:#"Contact" inManagedObjectContext:appDelegate.managedObjectContext];
request.predicate = [NSPredicate predicateWithFormat:#"contactNumber = %#", stringPhone];
NSError *executeFetchError = nil;
Contact *contact = [[appDelegate.managedObjectContext executeFetchRequest:request error:&executeFetchError] lastObject];
if (!contact)
{
contact = (Contact *)[NSEntityDescription insertNewObjectForEntityForName:#"Contact" inManagedObjectContext:appDelegate.managedObjectContext];
[contact setContactFirstName:firstName];
[contact setContactLastName:lastName];
if (firstName && lastName)
{
[contact setContactFullName:[NSString stringWithFormat:#"%# %#",firstName,lastName]];
}
else if(firstName)
{
[contact setContactFullName:firstName];
}
else
{
[contact setContactFullName:lastName];
}
[contact setContactType:phoneLabelLocalized];
[contact setContactDate:[NSDate date]];
[contact setContactOriginalNumber:phone];
[contact setContactNumber:stringPhone];
[contact setContactEmail:userEmail];
[arrayContacts addObject:stringPhone];
}
}
}
CFRelease(phoneNumbers);
NSError *error;
if (![appDelegate.managedObjectContext save:&error])
{
// This is a serious error saying the record could not be saved.
// Advise the user to restart the application
}
}
ABAddressBookRegisterExternalChangeCallback will give you a callback whenever the address book changes.
ABRecordGetRecordID gives you the unique identifier for the address book entry (scoped to the device, not globally unique).
Those two things are enough for you to detect records being modified and deleted.
First Set Callback
ABAddressBookRef callBackAddressBook = ABAddressBookCreate();
ABAddressBookRegisterExternalChangeCallback(callBackAddressBook, AddressBookExternalChangeCallback, self);
When notification occurs it will call below callback method
void AddressBookExternalChangeCallback (ABAddressBookRef callBackAddressBook,CFDictionaryRef info,void *context)
{
// use callBackAddressBook and get information about the changes
}

Retrieve contacts from iphone

I need to display all the list of contacts available in user's phone in UITableView.I can retrieve the contactName , PhoneNumber successfully.But when I add the data to NSMutableArray it adds some unusual characters.Could n;t understand wht the problem is
-(void)viewDidLoad
{
Names=[[NSMutableArray alloc]init];
ABAddressBookRef allPeople = ABAddressBookCreate();
CFArrayRef allContacts = ABAddressBookCopyArrayOfAllPeople(allPeople);
CFIndex numberOfContacts = ABAddressBookGetPersonCount(allPeople);
NSLog(#"numberOfContacts---%ld",numberOfContacts);
for(int i = 0; i < numberOfContacts; i++){
NSString* name = #"";
NSString* phone = #"";
NSString* email = #"";
ABRecordRef aPerson = CFArrayGetValueAtIndex(allContacts, i);
ABMultiValueRef fnameProperty = ABRecordCopyValue(aPerson, kABPersonFirstNameProperty);
ABMultiValueRef lnameProperty = ABRecordCopyValue(aPerson, kABPersonLastNameProperty);
ABMultiValueRef phoneProperty = ABRecordCopyValue(aPerson, kABPersonPhoneProperty);\
ABMultiValueRef emailProperty = ABRecordCopyValue(aPerson, kABPersonEmailProperty);
NSArray *emailArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSArray *phoneArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);
if (fnameProperty != nil) {
name = [NSString stringWithFormat:#"%#", fnameProperty];
}
if (lnameProperty != nil) {
name = [name stringByAppendingString:[NSString stringWithFormat:#" %#", lnameProperty]];
}
if ([phoneArray count] > 0) {
if ([phoneArray count] > 1) {
for (int i = 0; i < [phoneArray count]; i++) {
phone = [phone stringByAppendingString:[NSString stringWithFormat:#"%#\n", [phoneArray objectAtIndex:i]]];
}
}else {
phone = [NSString stringWithFormat:#"%#", [phoneArray objectAtIndex:0]];
}
}
if ([emailArray count] > 0) {
if ([emailArray count] > 1) {
for (int i = 0; i < [emailArray count]; i++) {
email = [email stringByAppendingString:[NSString stringWithFormat:#"%#\n", [emailArray objectAtIndex:i]]];
}
}else {
email = [NSString stringWithFormat:#"%#", [emailArray objectAtIndex:0]];
}
}
NSLog(#"NAME : %#",name);
NSLog(#"PHONE: %#",phone);
NSLog(#"EMAIL: %#",email);
NSLog(#"\n");
NSMutableDictionary *d=[[NSMutableDictionary alloc]init];
[d setObject:name forKey:#"Name"];
[d setObject:phone forKey:#"Phone"];
[d setObject:email forKey:#"Email"];
[Names addObject:d];
}
NSLog(#"%#",Names);
This is the NSLog of Names :
{
Email = "";
Name = Hk;
Phone = "(975)\U00a0050-1890"; //Actual Number (975)050-1890
},
{
Email = "";
Name = Nik;
Phone = "1\U00a0(234)\U00a0567-890"; //Actual Number :(932)324-1343
}
Why r unusual characters being added for Phone Number ...
Any help would be appreciated..
It is a "No-break space" (see http://unicode-table.com/en/00A0/).
It seems that such symbols can emerge in your address book via some external sync.
But I have no difference visually.
If you put in number in iPhone address book it will be automatically formatted with real unremovable space between parentheses and digits. It is not the case in your situation. You have no spaces at all visually. So in code you have no-break spaces.

Retrieve Phone number by using kABPersonPhoneProperty

I am not able to retrieve mobile number from below code, i am trying lots of thing but unable to solve it. please help me
//this below code is for saving mobile number and phone number
ABRecordRef newPerson = ABPersonCreate();
ABMultiValueAddValueAndLabel(phone, (__bridge CFTypeRef)(txtMob2.text), kABHomeLabel, NULL);
ABRecordSetValue(newPerson, kABPersonPhoneProperty, phone, &error);
//image
NSData *dataref = UIImagePNGRepresentation(imgProfile.image);
ABPersonSetImageData(newPerson, (__bridge CFDataRef)(dataref), &error);
ABAddressBookAddRecord(addressbook, newPerson, &error);
ABAddressBookSave(addressbook, nil);
CFRelease(newPerson);
// Now Below code is of displaying details.
- (void)displayContacts
{
int i;
appDelegate.arr_contact = [[NSMutableArray alloc] init];
ABAddressBookRef contactBook =ABAddressBookCreateWithOptions(nil, NULL);
NSArray *allData = (__bridge_transfer NSArray *)(ABAddressBookCopyArrayOfAllPeople(contactBook));
NSUInteger contactNum = 0;
NSInteger recordId;
ABRecordRef recId;
for (i =0; i < [allData count]; i++)
{
appDelegate.dict_contact =[[NSMutableDictionary alloc] init];
ABRecordRef ref =(__bridge ABRecordRef)(allData[i]);
//mobile no and phone no
ABMultiValueRef mobNum = ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFIndex PhoneCount = ABMultiValueGetCount(mobNum);
for (int k = 0; k <PhoneCount; k++) {
strMobile = (__bridge NSString *)(ABMultiValueCopyLabelAtIndex(mobNum, k));
strPhone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(mobNum, k));
if ([strMobile isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobileno = (__bridge NSString*)ABMultiValueCopyValueAtIndex(mobNum, k);
}
else if ([strPhone isEqualToString:(NSString *)kABHomeLabel])
{
phoneno = (__bridge NSString*)ABMultiValueCopyValueAtIndex(mobNum, k);
break;
}
NSLog(#"Mobile: %# phone: %#, %#",mobileno, phoneno, strPhone);
[appDelegate.dict_contact setObject:[NSString stringWithFormat:#"%#",mobileno] forKey:#"mobno"];
[appDelegate.dict_contact setObject:[NSString stringWithFormat:#"%#",phoneno] forKey:#"phnno"];
}
//image
NSData *imgData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(ref, kABPersonImageFormatThumbnail);
UIImage *image;
if (imgData)
{
image = [UIImage imageWithData:imgData];
NSLog(#"add image: %#",image);
}else
{
image = [UIImage imageNamed:#"dummy.png"];
}
[appDelegate.dict_contact setObject:image forKey:#"image"];
[appDelegate.arr_contact addObject:appDelegate.dict_contact];
}
}
Please check my edited code.
Please See this code....
-(void)GetAddressBook
{
Contacts = [[NSMutableArray alloc]init];
if (ABAddressBookCreateWithOptions) {
#try {
ABAddressBookRef addressBook = ABAddressBookCreate();
// NSArray *people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
if (!addressBook) {
NSLog(#"opening address book");
}
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSLog(#"opening address book ==%ld",nPeople);
for (int i=0;i < nPeople;i++) {
NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
NSString *Contact;
ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));
CFStringRef firstName, lastName;
NSMutableArray *array = [[NSMutableArray alloc]init];
NSString *email;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
ABMultiValueRef multiValueRef = ABRecordCopyValue(ref, kABPersonEmailProperty);
array = [(__bridge NSMutableArray *)ABMultiValueCopyArrayOfAllValues(multiValueRef) mutableCopy];
email = ([array count] > 0) ? array[0] : #"";
if(firstName)
{
Contact = [NSString stringWithFormat:#"%#", firstName];
if(lastName)
Contact = [NSString stringWithFormat:#"%# %#",firstName,lastName];
}
[dOfPerson setObject:Contact forKey:#"name"];
[dOfPerson setObject:[NSString stringWithFormat:#"%d", i] forKey:#"id"];
[dOfPerson setObject:[NSString stringWithFormat:#"%#",#""] forKey:#"found"];
[dOfPerson setObject:email forKey:#"email"];
NSString* mobileLabel;
for(CFIndex j = 0; j< ABMultiValueGetCount(phones); j++)
{
mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phones, j);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
[dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:#"Phone"];
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
[dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:#"Phone"];
break ;
}
}
[Contacts addObject:dOfPerson];
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
dispatch_async(dispatch_get_main_queue(), ^{
});
Here you will get Phone number, First Name, Last name and Email Id. Here Contacts is an NSMutableArray. Also view this answer for a complete set of code.
contact details from ipad using objective-c
Try This In this code I'm getting both the name and mobile number if you want the mobile number only use this kABPersonPhoneProperty:
CFErrorRef * error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
for (int i=0;i < nPeople;i++)
{
NSString* name;
NSMutableDictionary* tempContactDic = [NSMutableDictionary new];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
CFStringRef firstName;
firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
name = (__bridge NSString *)(firstName);
[tempContactDic setValue:name forKey:#"name"];
//fetch email id
NSString *strEmail;
NSMutableString* strMobile;
ABMultiValueRef email = ABRecordCopyValue(ref, kABPersonPhoneProperty);
CFStringRef tempEmailref = ABMultiValueCopyValueAtIndex(email, 0);
strEmail = (__bridge NSString *)tempEmailref;
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"-" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"(" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#")" withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#" " withString:#""];
strEmail = [strEmail stringByReplacingOccurrencesOfString:#"+" withString:#""];
strMobile = [[NSMutableString alloc] initWithString:strEmail];
if ([strEmail length] == 10) {
[strMobile insertString:#"91" atIndex:0];
}
else {
}
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:strMobile];
[tempContactDic setValue:myNumber forKey:#"phone"];
[contactsArray addObject:tempContactDic];
}
/// With below two steps of code you'll get the contacts in alphabetical order
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
[contactsArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

Goto address book/contact number directly from app

I want to make an app and want to access the contact numbers directly when i touch/press a particular text field or button and then return to my app with a selected contact number. How can i do this.
You need to add ABPeoplePickerNavigationControllerDelegate delegate in .h file
and in .m file write down below three methods:
#pragma mark People Picker Delegate Methods
- (void)peoplePickerNavigationControllerDidCancel:
(ABPeoplePickerNavigationController *)peoplePicker {
[peoplePicker dismissModalViewControllerAnimated:YES];
[peoplePicker autorelease];
}
- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person {
return YES;
}
- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)valueID{
ABPropertyType type = ABPersonGetTypeOfProperty(property);
if (type==kABMultiDictionaryPropertyType) {
ABMutableMultiValueRef multi = ABRecordCopyValue(person, property);
CFIndex index = ABMultiValueGetIndexForIdentifier(multi, valueID);
CFDictionaryRef dic = ABMultiValueCopyValueAtIndex(multi, index);
CFStringRef street = CFDictionaryGetValue(dic, kABPersonAddressStreetKey);
NSString* StreetName =(NSString*)street;
streetNameText.text=StreetName;
NSLog(#"StreetName:%#",StreetName);
NSRange range = NSMakeRange (0, 5);
NSLog (#"Beer shortname: %#", [StreetName substringWithRange:range]);
int val = [StreetName intValue];
NSLog(#"StreetName:%d",val);
NSString *newChange = [[NSString alloc] initWithFormat:#"%d", val];
streetNOText.text = newChange;
[newChange release];
CFRelease(dic);
CFRelease(multi);
}
[self dismissModalViewControllerAnimated:YES];
return NO;
}
I am not able to give you the whole code. Following bare the steps :
1. On click to button go to new view which must have tableview
2. In that view get the address book
To get the addressbook
Add these frameworks:
AddressBook,
AddressBookUI
import them in your view
And for getting the contacts from addressbook refer the following tutorial
http://developer.apple.com/library/ios/#documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/Chapters/QuickStart.html#//apple_ref/doc/uid/TP40007744-CH2-SW1
I know this is not the full solution for your question but this link will help you to get the remaining task...Good luck
May this method will help you, just call this method when you want to fetch records from addressbook. n ofcourse add the frameworks AddressBook, AddressBookUI
first create database (as i did if you want you can store it into NSMutable Array instead of database, as per your requirement.)
-(void)fetchRecordsFromAddressBook
{
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
//NSArray *addresses = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
// [arrayContacts removeAllObjects];
[self emptyDataContext];
for (int i = 0; i < nPeople; i++)
{
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);
////////////////// get first name ///////////////////
CFStringRef firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
CFStringRef lastName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
CFStringRef nickName = ABRecordCopyValue(ref, kABPersonNicknameProperty);
CFStringRef middleName = ABRecordCopyValue(ref, kABPersonMiddleNameProperty);
////////////////// get image ///////////////////
// ABMultiValueRef ContactImage = (ABMultiValueRef) ABRecordCopyValue(ref,kABPersonImageFormatThumbnail);
NSData *data=nil;
// NSLog(#"Image Testing is : %#",ref);
if(ABPersonHasImageData(ref))
{
data = [(NSData *) ABPersonCopyImageData(ref) autorelease];
if(data)
{
// NSLog(#"Im Testing is : %#",data);
//image = [[UIImage alloc] initWithData:data];
}
}
// NSLog(#"Image is : %#",ContactImage);
// NSLog(#" Name is : %#",firstName);
////////////////// get email ///////////////////
ABMultiValueRef emails = (ABMultiValueRef) ABRecordCopyValue(ref, kABPersonEmailProperty);
NSString *emailID=#"";
if(ABMultiValueGetCount(emails)>=1)
{
emailID = (NSString *)ABMultiValueCopyValueAtIndex(emails,0);
}
////////////////// get phone number ///////////////////
ABMultiValueRef phones = (ABMultiValueRef) ABRecordCopyValue(ref, kABPersonPhoneProperty);
NSString *phone=#"";
NSString *homeNumber = #"";
NSString *worknumber = #"";
if(ABMultiValueGetCount(phones)>=1)
{
//int ph = [ABMultiValueCopyValueAtIndex(phones, 0) intValue];
phone = (NSString *)ABMultiValueCopyValueAtIndex(phones,0);
}
// NSLog(#"%#",(NSString*)phone);
if(ABMultiValueGetCount(phones)>=2)
{
homeNumber = (NSString *)ABMultiValueCopyValueAtIndex(phones,1);
}
if(ABMultiValueGetCount(phones)>=3)
{
worknumber = (NSString *)ABMultiValueCopyValueAtIndex(phones,2);
}
NSMutableArray *arrayContacts = [[NSMutableArray alloc] init ];
///////////////////////////// insert into array ////////////////////////////
arrayContacts = [CoreDataAPIMethods getObjectsFromContext:#"AllContactData" :#"Index" :NO :self.managedObjectContext];
//////////////////////////// insert Index ///////////////////////////////
int NewEntryID;
if ([arrayContacts count] > 0)
{
AllContactData * Contacdata = [arrayContacts objectAtIndex:0];
NewEntryID = [Contacdata.Index intValue] +1;
}
else
{
NewEntryID = 1;
}
NSString *capitalisedSentence =
[(NSString *)firstName stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[(NSString *)firstName substringToIndex:1] capitalizedString]];
AllContactData *Contactitem=(AllContactData *)[NSEntityDescription insertNewObjectForEntityForName:#"AllContactData" inManagedObjectContext:self.managedObjectContext];
// NSLog(#"%#",capitalisedSentence);
Contactitem.Name = capitalisedSentence;
Contactitem.LastName = (NSString*)lastName;
Contactitem.NickName = (NSString*)nickName;
Contactitem.MiddleName = (NSString*)middleName;
Contactitem.Email=(NSString*)emailID;
phone = [phone stringByReplacingOccurrencesOfString:#"(" withString:#""];
phone = [phone stringByReplacingOccurrencesOfString:#")" withString:#""];
phone = [phone stringByReplacingOccurrencesOfString:#"+" withString:#""];
phone = [phone stringByReplacingOccurrencesOfString:#" " withString:#""];
phone = [phone stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSLog(#"The Replaced String is : %#", phone);
Contactitem.PhoneNumber=(NSString*)phone;
Contactitem.HomeNumber=(NSString*)homeNumber;
Contactitem.WorkNumber=(NSString*)worknumber;
Contactitem.Index = [NSNumber numberWithInt:NewEntryID];
Contactitem.Image = data;
// NSLog(#"Image in databse is : %#",(NSData *)ContactImage);
if(firstName!=nil)
{
CFRelease(firstName);
}
CFRelease(ref);
}
CFRelease(allPeople);
///////////////////////////// save entries ////////////////////////////
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error...
}
}