http://blogs.embarcadero.com/ao/2012/01/24/39203


iOS Address Book fun

Getting data out of the iOS address book is a lot harder than I thought… Must make component… ;)

Here’s a Q&D routine I managed to eek out today. It simply prints all contacts and all their numbers to the log console.

Enjoy!

uses
  iPhoneAll, AddressBook, CFArray, CFBase;

procedure DumpAddressBook;
var
  addressBook : ABAddressBookRef;
  allPeople : CFArrayRef;
  nPeople : CFIndex;
  ref : ABRecordRef;
  i, j : Integer;
  firstName : CFStringRef;
  lastName : CFStringRef;
  phoneNumber : CFStringRef;
  l, v : CFStringRef;
  S : NSString;
begin
  addressBook := ABAddressBookCreate;
  allPeople := ABAddressBookCopyArrayOfAllPeople(addressBook);
  nPeople := ABAddressBookGetPersonCount(addressBook);

  for i:=0 to nPeople-1 do begin
    ref := CFArrayGetValueAtIndex(allPeople,i);

    firstName := ABRecordCopyValue(ref,kABPersonFirstNameProperty);
    lastName := ABRecordCopyValue(ref,kABPersonLastNameProperty);
    if firstName <> nil then
      if lastName <> nil then
        S := NSString.stringWithFormat(NSSTR(PChar('%@, %@')),lastName,firstName)
      else
        S := NSString.stringWithFormat(NSSTR(PChar('%@')),firstName)
    else
      if lastName <> nil then
        S := NSString.stringWithFormat(NSSTR(PChar('%@')),lastName);
    NSLog(S);

    phoneNumber := ABRecordCopyValue(ref, kABPersonPhoneProperty);
    for j:=0 to ABMultiValueGetCount(phoneNumber)-1 do begin
      l := ABMultiValueCopyLabelAtIndex(phoneNumber,j);
      v := ABMultiValueCopyValueAtIndex(phoneNumber,j);
      S := NSString.stringWithFormat(NSSTR(PChar('%@: %@')),l,v);
      NSLog(S);
      CFRelease(l);
      CFRelease(v);
    end;

    if phoneNumber <> nil then
      CFRelease(phoneNumber);
    if firstName <> nil then
      CFRelease(firstName);
    if lastName <> nil then
      CFRelease(lastName);
  end;
end;