i m using following code for Backup Full Address Book.
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
CFArrayRef peopleForBackup = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFDataRef vcards = (CFDataRef)ABPersonCreateVCardRepresentationWithPeople(peopleForBackup);
NSString *vcardString = [[NSString alloc] initWithData:(NSData *)CFBridgingRelease(vcards) encoding:NSUTF8StringEncoding];
in Above code i can not get Notes from Contacts.
Please help me, how can i take a full address book as a Backup..?
get Complete Address Book ,
-(void)getAddressbookContacts
{
//Get Contacts From PhoneBook Contacts
NSString *fullName;
UIImage *img;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, nil);
NSInteger numberOfPeople = ABAddressBookGetPersonCount(addressBook);
NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
for (NSInteger i = 0; i < numberOfPeople; i++) {
ABRecordRef person = (__bridge ABRecordRef)allPeople[i];
// get phone numbers
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobile=#"";
NSString* mobileLabel;
CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
for (CFIndex i = 0; i < numberOfPhoneNumbers; i++)
{
mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phoneNumbers, i);
// NSLog(#"mobileLabel=%#",mobileLabel);
//Only add numbers who have saved in Mobile or IPhone (eg.Home,Work,..)
if([mobileLabel isEqualToString:(__bridge NSString *)kABPersonPhoneMobileLabel] || [mobileLabel isEqualToString:(__bridge NSString *)kABPersonPhoneIPhoneLabel])
{
NSString *phoneNumber = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, i));
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
// phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
// NSLog(#"phoneNumber=%#",phoneNumber);
// contact number should be mobile number or iphone
mobile = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, i);
NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
// ABMultiValueRef emailMultiValue = ABRecordCopyValue(person, kABPersonEmailProperty);
//Fetch Email Address of Contact
// NSArray *emailAddresses = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailMultiValue);
//NSLog(#"email is %#",emailAddresses);
//Fetch Image of Contact
NSData *imgData = (__bridge NSData *)ABPersonCopyImageData(person);
if(lastName == nil)
{
fullName = firstName;
}
else
{
fullName = [firstName stringByAppendingString:#" "];
fullName = [fullName stringByAppendingString:lastName];
}
if(imgData == nil)
{
//NSLog(#"no image found");
img = [UIImage imageNamed:#"contact"];
}
else
{
img = [UIImage imageWithData:imgData];
}
NSMutableDictionary *dictContactDetails = [[NSMutableDictionary alloc]init];
[dictContactDetails setValue:fullName forKey:#"full_name"];
[dictContactDetails setValue:img forKey:#"profile_image"];
[dictContactDetails setValue:mobile forKey:#"mobile_number"];
[dictContactDetails setValue:phoneNumber forKey:#"number"];
//Add Fullname,Image & number into Array & Display it into Table
[arrayOfInviteContacts addObject:dictContactDetails];
}
}
CFRelease(phoneNumbers);
}
NSLog(#"arrayOfInviteContacts=%lu, %#",(unsigned long)arrayOfInviteContacts.count,arrayOfInviteContacts);
[tblInviteFriends reloadData];
}
Related
As i guess this is a very simple and basic question.
i am using #import <AddressBook/AddressBook.h> to get the contact info of device and i had successfully implemented the same.
Everythings work fine when i got one phone no and one email from each contact. But when i got multiple phone no's and multiple email then getting crash on my app. I guess i am not using the proper saving method.
So i really want to know how to save one name string and one array of email(different length) and phone no(different length) as group for a contact and same for all other. so that it would not be difficult to reproduce the result later on the detail screen
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
[values1 addObject:[NSString stringWithFormat:#"%# %#",firstName,lastName]]; //values1 array to save name of contact
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++) {
NSString* email = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j);
NSLog(#"Email:%#", email);
[values2 addObject:[NSString stringWithFormat:#"%#",email]];
} //values2 array to save email associated to that contact
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
NSLog(#"phone:%#", phoneNumber);
[values3 addObject:[NSString stringWithFormat:#"%#",phoneNumber]];
}//values3 array to save different phone no's associated to that contacts
NSDictionary *dict = [[NSDictionary alloc]init];
}
AS now i have three array with details contain details of one contact. Now how can merge these three array values to one so that it would be easy to save and fetch data for multiples or hundreds of contacts
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");
}
You can see multiple contact and email in log if contact have.
I need to make a UITableView which fetches address book contents in it and also a UISearchBar which searches the address book contents.
I need an implementation like this project
http://www.appcoda.com/search-bar-tutorial-ios7/
But the problem is here the data is static and I want to load address book's data in it.
I have created ContactData NSObject Class. In following method, I am creating its object for each contact. At the end, you will get NSMutableArray named contactArr.
-(void)loadContacts{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//NSLog(#"%#", addressBook);
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++) {
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
ContactData *dataObj = [[ContactData alloc]init];
NSString *Name = #" ";
if ([firstName length]>0) {
if ([lastName length]>0) {
Name = [NSString stringWithFormat:#"%# %#",firstName,lastName];
}
else{
Name = firstName;
}
}
else{
Name = #" ";
}
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
[[UIDevice currentDevice] name];
//NSLog(#"\n%#\n", [[UIDevice currentDevice] name]);
NSString *phoneNumber = #" ";
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
}
ABMultiValueRef Emails = ABRecordCopyValue(person, kABPersonEmailProperty);
[[UIDevice currentDevice] name];
NSString *Email; //= #" ";
for (CFIndex i = 0; i < ABMultiValueGetCount(Emails); i++) {
Email = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(Emails, i);
}
ABMultiValueRef Addresses = ABRecordCopyValue(person, kABPersonAddressProperty);
NSString *address = #" ";
NSMutableDictionary* addressDict = [[NSMutableDictionary alloc]init];
for (CFIndex i = 0; i < ABMultiValueGetCount(Addresses); i++) {
addressDict = (__bridge_transfer NSMutableDictionary *) ABMultiValueCopyValueAtIndex(Addresses, i);
//NSLog(#"address = %#", addressDict);
NSString * street = [addressDict objectForKey:#"Street"];
NSString * city = [addressDict objectForKey:#"City"];
NSString * state = [addressDict objectForKey:#"State"];
NSString *country = [addressDict objectForKey:#"Country"];
if (country.length>0 || state.length>0 || city.length>0 || street.length>0) {
if (country.length>0 && state.length>0) {
address = [NSString stringWithFormat:#"%#, %#", state,country];
}
else if(country.length>0 && city.length>0){
address = [NSString stringWithFormat:#"%#, %#", city,country];
}
else if (state.length>0 && street.length>0){
address = [NSString stringWithFormat:#"%#, %#", street,country];
}
else if (state.length>0 && city.length>0){
address = [NSString stringWithFormat:#"%#, %#", city,state];
}
else if (state.length>0 && street.length>0){
address = [NSString stringWithFormat:#"%#, %#", street,state];
}
else if (city.length>0 && street.length>0){
address = [NSString stringWithFormat:#"%#, %#", street,city];
}
else if (country.length>0){
address = country;
}
else if (state.length>0){
address = state;
}
else if (city.length>0){
address = city;
}
}
else{
address = #" ";
}
}
//NSLog(#"address = %#", address);
NSData *imgData = (__bridge_transfer NSData *) ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
dataObj.name = Name;
dataObj.email = Email;
dataObj.phone = phoneNumber;
dataObj.imageData = imgData;
dataObj.address = address;
[contactArr addObject:dataObj];
}
NSLog(#"contacts loaded");
//NSLog(#"count = %lu", (unsigned long)contactArr.count);
}
else {
//Go to settings and allow access to use contacts[GlobalFunction removeWaitView];
}
}
First make sure you have the correct frameworks imported:
#import <AddressBook/AddressBook.h>
Fetch the contacts of AddressBook like this:
ABAddressBookRef addressBook = ABAddressBookCreate( );
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople( addressBook );
CFIndex nPeople = ABAddressBookGetPersonCount( addressBook );
for ( int i = 0; i < nPeople; i++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex( allPeople, i );
//further code
}
Then populate the UITableView as usual (as per the example you already provided).
Thankfully this framework is being deprecated. The new Contacts API in iOS 9 is gorgeous.
How can i Edit Specific Address book First Name and Last Name Programatically .Could any one Guide me to found this.
Am getting Contact Recode like below.
Email = (
"John-Appleseed#mac.com"
);
First = John;
Last = Appleseed;
numbers = (
"888-555-5512",
"888-555-1212"
);
}
How can i edit the First and last Values.
I used Below code to Fetch contact details from Device
CFErrorRef * error = NULL;
addressBook = ABAddressBookCreateWithOptions(NULL, error);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
if (granted)
{
dispatch_async(dispatch_get_main_queue(), ^{
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++){
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSString *name=[NSString stringWithFormat:#"%# %#",firstName,lastName];
NSString *Birthday=(__bridge NSString *)(ABRecordCopyValue(person, kABPersonBirthdayProperty));
NSLog(#"Name:%# %# %#", firstName, lastName,Birthday);
//For Email ids
NSMutableArray *Emails = [NSMutableArray array];
ABMutableMultiValueRef eMail = (__bridge ABMutableMultiValueRef)((__bridge NSString *) ABRecordCopyValue(person, kABPersonEmailProperty));
for (CFIndex i = 0; i < ABMultiValueGetCount(eMail); i++) {
NSString *emails = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(eMail, i);
[Emails addObject:emails];
}
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSMutableArray *numbers = [NSMutableArray array];
for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
[numbers addObject:phoneNumber];
}
NSMutableDictionary *contact = [NSMutableDictionary dictionary];
[contact setObject:firstName forKey:#"First"];
[contact setObject:lastName forKey:#"Last"];
[contact setObject:numbers forKey:#"numbers"];
[contact setObject:Emails forKey:#"Email"];
NSLog(#" contacts are %#",contact);
[all_contacts addObject:contact];
NSLog(#"all contacts are %#",all_contacts);
[self.tbl_contacts reloadData];
}
});
}
});
First pick the required contact:
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
[self peoplePickerNavigationController:peoplePicker didSelectPerson:person];
return NO;
}
Refer this: for setting and getting first name and last name
ABRecordRef aRecord = ABPersonCreate();
CFErrorRef anError = NULL;
bool didSet;
didSet = ABRecordSetValue(aRecord, kABPersonFirstNameProperty, CFSTR("Katie"), &anError);
if (!didSet) {/* Handle error here. */}
didSet = ABRecordSetValue(aRecord, kABPersonLastNameProperty, CFSTR("Bell"), &anError);
if (!didSet) {/* Handle error here. */}
CFStringRef firstName, lastName;
firstName = ABRecordCopyValue(aRecord, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(aRecord, kABPersonLastNameProperty);
/* ... Do something with firstName and lastName. ... */
CFRelease(aRecord);
CFRelease(firstName);
CFRelease(lastName);
I am having the trouble to fetch iPhone contacts.
I have tried to fetch the contact by the following code.
It is working fine in simulator and also worked fine when the contacts are less in the contact list.
In my phone I am having 1000 Contacts. So it crashes on this device. Please guide me if you know the reason.
Here is my code.
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];
for (int i = 0; i < nPeople; i++)
{
NSMutableDictionary *dicContacts = [[NSMutableDictionary alloc]init];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
[phoneNumbers addObject:phoneNumber];
//NSLog(#"All numbers %#", phoneNumbers);
}
if ([phoneNumbers count] > 0) {
[dicContacts setValue:[phoneNumbers objectAtIndex:0] forKeyPath:#"Contact"];
}
[items addObject:dicContacts];
}
Thanks In Advance
-(void)tkPeoplePickerController:(TKPeoplePickerController*)picker didFinishPickingDataWithInfo:(NSArray*)contacts
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL,error);
[contacts enumerateObjectsUsingBlock:^(id obj,NSUInteger idx, BOOL *stop)
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
TKContact *contact = (TKContact*)obj;
NSNumber *personID = [NSNumber numberWithInt:contact.recordID];
ABRecordID abRecordID = (ABRecordID)[personID intValue];
ABRecordRef abPerson = ABAddressBookGetPersonWithRecordID(addressBook, abRecordID);
// Check person image
UIImage *personImage = nil;
if (abPerson != nil && ABPersonHasImageData(abPerson))
{
if ( &ABPersonCopyImageDataWithFormat != nil )
{
// iOS >= 4.1
CFDataRef contactThumbnailData = ABPersonCopyImageDataWithFormat(abPerson, kABPersonImageFormatThumbnail);
personImage = [UIImage imageWithData:(__bridge NSData*)contactThumbnailData];
CFRelease(contactThumbnailData);
ABMultiValueRef emailValues = ABRecordCopyValue(abPerson, kABPersonEmailProperty);
// This is how you extract the first item from the multivalues:
CFStringRef cfEmailAddress = ABMultiValueCopyValueAtIndex(emailValues, 0);
// This is how you convert it to an NSString.
[RSVP_ImageArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
contact.name,#"name",
contact.email,#"email",
[NSString stringWithFormat:#"%d",abRecordID],#"recodeID",
savedImagePath,#"Image",
nil]];
CFDataRef contactImageData = ABPersonCopyImageDataWithFormat(abPerson, kABPersonImageFormatOriginalSize);
CFRelease(contactImageData);
}
else
{
// iOS < 4.1
CFDataRef contactImageData = ABPersonCopyImageData(abPerson);
personImage = [[UIImage imageWithData:(__bridge NSData*)contactImageData] thumbnailImage:CGSizeMake(thumbnailSize, thumbnailSize)];
ABMultiValueRef emailValues = ABRecordCopyValue(abPerson, kABPersonEmailProperty);
// This is how you extract the first item from the multivalues:
CFStringRef cfEmailAddress = ABMultiValueCopyValueAtIndex(emailValues, 0);
// This is how you convert it to an NSString.
[RSVP_ImageArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
contact.name,#"name",
contact.email,#"email",
[NSString stringWithFormat:#"%d",abRecordID],#"recodeID",
savedImagePath,#"Image",
nil]];
CFRelease(contactImageData);
}
}
else
{
ABMultiValueRef emailValues = ABRecordCopyValue(abPerson, kABPersonEmailProperty);
// This is how you extract the first item from the multivalues:
CFStringRef cfEmailAddress = ABMultiValueCopyValueAtIndex(emailValues, 0);
// This is how you convert it to an NSString.
[mutablearray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
contact.name,#"name",
contact.email,#"email",
[NSString stringWithFormat:#"%d",abRecordID],#"recodeID",
savedImagePath,#"Image",
nil]];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
});
[pool drain];
}];
dispatch_async(dispatch_get_main_queue(), ^{
CFRelease(addressBook);
});
});
}
Use this code with it will surely help you.. for reference u can use this link https://github.com/qnibus/TKContactsMultiPicker ... :)
for(CFIndex i=0;i<ABMultiValueGetCount(multiPhones);i++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
[phoneNumbers addObject:[NSString stringWithFormat:#"%#",phoneNumber]];
//NSLog(#"All numbers %#", phoneNumbers);
}
[phoneNumbers retain];
I'm using ABAddressBookCreateWithOptions and ABAddressBookCopyArrayOfAllPeople to achieve all contacts' informations.
I can get person's full name, emails and phone numbers like that:
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for (CFIndex i = 0; i < CFArrayGetCount(people); i++)
{
ABRecordRef person = CFArrayGetValueAtIndex(people, i);
////get full name////
NSString *fullname = #"";
if (ABRecordCopyValue(person, kABPersonFirstNameProperty)!=NULL){
fullname = [NSString stringWithFormat:#"%# ", ABRecordCopyValue(person, kABPersonFirstNameProperty)];
}
if (ABRecordCopyValue(person, kABPersonMiddleNameProperty)!=NULL){
fullname = [NSString stringWithFormat:#"%#%# ", fullname,ABRecordCopyValue(person, kABPersonMiddleNameProperty)];
}
if (ABRecordCopyValue(person, kABPersonLastNameProperty)!=NULL){
fullname = [NSString stringWithFormat:#"%#%#", fullname,ABRecordCopyValue(person, kABPersonLastNameProperty)];
}
fullname = [fullname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"fullname: %#",fullname);
////get phone numbers////
ABMultiValueRef phonenumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
if (ABMultiValueGetCount(phonenumbers)>0)
{
for (CFIndex j=0; j < ABMultiValueGetCount(phonenumbers); j++)
{
NSString *phonenumber = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phonenumbers, j));
NSLog(#"phone number: %#",phonenumber);
}
}
CFRelease(phonenumbers);
////get emails////
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
if (ABMultiValueGetCount(emails)>0)
{
for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++)
{
NSString *email = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(emails, j));
NSLog(#"email: %#",email);
}
}
CFRelease(emails);
}
CFRelease(addressBook);
CFRelease(people);
Everything works perfectly. But I need to create a JSON object with these informations like that:
[{"name":"Christine Work","phone_numbers":["+99023424234"]},{"name":"Alex Bla","phone_numbers":["+135352125262","+13433452347"],"email_addresses":["bla#bla.com","bla2#bla2.com"]}]
Scenario: If person has email address, than add it to json object, if not, not incude it in json.
If person has more than one phone number or more than one email address add all of them to json.
I'm stuck right here. I know how can I create a json object with NSDictionary :
NSError *error;
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
#"alex", #"name",
#"+90225252", #"phones",
nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:info encoding:NSUTF8StringEncoding];
but how can I integrate this code to my scenario in the loop.
Give this a go. Added the necessary code to create the JSON on top of your code. If there are no phone numbers or emails for a contact, NSNull is added for that key. Make sure to check for it when you are pulling the data out of the JSON. Didn't build the code, so let me know if you run into any errors.
NSMutableArray *usersArray = [[NSMutableArray alloc] init];
NSMutableDictionary *singleUserDictionary = [[NSMutableDictionary alloc] init];
NSMutableArray *phoneNumbersArray = [[NSMutableArray alloc] init];
NSMutableArray *emailArray = [[NSMutableArray alloc] init];
for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
ABRecordRef person = CFArrayGetValueAtIndex(people, i);
////get full name////
NSString *fullname = #"";
if (ABRecordCopyValue(person, kABPersonFirstNameProperty)!=NULL){
fullname = [NSString stringWithFormat:#"%# ", ABRecordCopyValue(person, kABPersonFirstNameProperty)];
}
if (ABRecordCopyValue(person, kABPersonMiddleNameProperty)!=NULL){
fullname = [NSString stringWithFormat:#"%#%# ", fullname,ABRecordCopyValue(person, kABPersonMiddleNameProperty)];
}
if (ABRecordCopyValue(person, kABPersonLastNameProperty)!=NULL){
fullname = [NSString stringWithFormat:#"%#%#", fullname,ABRecordCopyValue(person, kABPersonLastNameProperty)];
}
fullname = [fullname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"fullname: %#",fullname);
[singleUserDictionary setObject:fullname forKey:#"name"];
////get phone numbers////
ABMultiValueRef phonenumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
if (ABMultiValueGetCount(phonenumbers)>0)
{
for (CFIndex j=0; j < ABMultiValueGetCount(phonenumbers); j++)
{
NSString *phonenumber = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phonenumbers, j));
NSLog(#"phone number: %#",phonenumber);
[phoneNumbersArray addObject:phonenumber];
}
}
else
[phoneNumbersArray addObject:[NSNull null]];
[singleUserDictionary setObject:phoneNumbersArray forKey:#"phone_numbers"];
CFRelease(phonenumbers);
////get emails////
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
if (ABMultiValueGetCount(emails)>0)
{
for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++)
{
NSString *email = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(emails, j));
NSLog(#"email: %#",email);
[emailArray addObject:email];
}
}
else
[emailArray addObject:[NSNull null]];
[singleUserDictionary setObject:emailArray forKey:#"email_addresses"];
CFRelease(emails);
[usersArray addObject:[NSDictionary dictionaryWithDictionary:singleUserDictionary]];
[singleUserDictionary removeAllObjects];
[phoneNumbersArray removeAllObjects];
[emailArray removeAllObjects];
}
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:usersArray options:0 error:&error];
if (error) {
//json success
}
CFRelease(addressBook);
CFRelease(people);
Pseudo-code:
Create outer NSMutableArray.
For each person --
create NSMutableDictionary
insert name
create NSMutableArray and insert into it phone numbers
insert the array into dictionary as "phone_numbers"
repeat for email addresses (if present)
insert dictionary into array
Run outer array through NSJSONSerialization to serialize into an NSData object