Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top