Wednesday, February 11, 2015

Adding a contact to iOS AddressBook using your Delphi application

















Now, I want to learn how to add a contact to your iOS Phone AddressBook!
First download my last source code from :
https://sourceforge.net/p/dpfdelphiios/code/
and see AddressBookAdd demo,

I added AddAddressBook procedure to TDPFAddressBook component :

  

function TDPFAddressBook.AddAddressBook( FirstName: string; LatName: string; PhoneNumbers: array of TPhoneNumbers ): Boolean;
var
  Person               : ABRecordRef;
  error                : CFErrorRef;
  addressBook          : ABAddressBookRef;
  phoneNumberMultiValue: ABMutableMultiValueRef;
  venuePhoneNumbers    : NSMutableArray;
  I                    : Integer;
  s                    : string;
begin
  result      := false;
  addressBook := ABAddressBookCreateWithOptions( nil, &error );
  Person      := ABPersonCreate;
  if not Assigned( Person ) then
    exit;

  // FirsName & LastName
  result := ABRecordSetValue( Person, 0, PNSSTR( FirstName ), &error );
  if not result then
    exit;
  result := ABRecordSetValue( Person, 1, PNSSTR( LatName ), &error );
  if not result then
    exit;
  result := ABAddressBookAddRecord( addressBook, Person, &error );
  if not result then
    exit;

  // Phone
  phoneNumberMultiValue := ABMultiValueCreateMutable( kABMultiStringPropertyType );
  for I                 := low( PhoneNumbers ) to high( PhoneNumbers ) do
  begin
    if PhoneNumbers[I].PhoneLabel = '' then
      PhoneNumbers[I].PhoneLabel := kABPersonPhoneMainLabel;
    ABMultiValueAddValueAndLabel( phoneNumberMultiValue, PNSSTR( PhoneNumbers[I].PhoneNumber ), CFSTR( PhoneNumbers[I].PhoneLabel ), 0 );
  end;
  result := ABRecordSetValue( person, 3, phoneNumberMultiValue, nil );
  CFRelease( phoneNumberMultiValue );

  if not result then
    exit;

  // Save to AddressBook
  if ABAddressBookHasUnsavedChanges( addressBook ) then
    result := ABAddressBookSave( addressBook, &error );

  exit;
end;


for using this function, you can call like this:

procedure TFPeoplePicker.DPFAddressBook1RequestAccess( Sender: TObject; const Granted: Boolean );
var
  p: array [0 .. 2] of TPhoneNumbers;
begin
  P[0].PhoneNumber := '+98912xxxxx';
  P[0].PhoneLabel  := 'mobile';

  P[1].PhoneNumber := '+982188xxxxx';
  P[1].PhoneLabel  := 'work';

  P[2].PhoneNumber := '+982188xxxxx';
  P[2].PhoneLabel  := ''; // <-- contact’s primary number

  if Granted then
    DPFAddressBook1.AddAddressBook( 'Babak', 'Yaghoobi', p )
  else
    ShowMessage( 'Go to Setting->Privacy->Contacts and switch on this application' );
end;


Finally, see your phone contact list:



Enjoy Delphi iOS Native Programming !

No comments:

Post a Comment