How to iteratively create PhoneGap contacts

I started a new project today to load the contacts from my personal database into my iPhone.

cd ~/Documents/pcrepo/aman-importer
phonegap create phonegap-test
cd phonegap-test
phonegap platform add ios
phonegap plugin add org.apache.cordova.contacts

There is documentation for the Contacts API.

The trouble I got into was iteratively creating contacts.

Code like this doesn’t work:

for ( var i in contact_data_list ) {
  var contact_data = contact_data_list[ i ];
  var contact = navigator.contacts.create();
  var name = new ContactName();
  name.givenName = contact_data.first_name;
  name.familyName = contact_data.last_name;
  contact.name = name;
  contact.save(
    function() { alert( 'saved!' ); },
    function() { alert( 'failed!' ); }
  );
}

The behavior is that contact.save fails and neither of the success or failure callbacks are invoked.

The way to iterate over the input data is like this:

var index = 0;
var saver = function() {
  if ( index === contact_data_list.length ) {
    // we're finished enumerating the array, we can report and exit:
    navigator.contacts.find( ['*'], report_contacts );
    return;
  }
  var contact_data = contact_data_list[ index++ ];
  var contact = navigator.contacts.create();
  var name = new ContactName();
  name.givenName = contact_data.first_name;
  name.familyName = contact_data.last_name;
  contact.name = name;
  contact.save(
    saver,
    function() { alert( 'failed!' ); }
  );
};
saver();

You can see it for real over here

Leave a Reply