How to access address book / contacts on iOS?

Hi there.

I have installed the cordova contacts plugin and have tried all I can find to access the contacts on the iOS address book but nothing I do works.

I would expect a prompt to appear saying ‘this app would like to access your address book’ etc at the very least, but I can’t even get that to show up.

Can anyone point me in a direction of some clearer example code / guide?

Basically I have created the ionic tabs app. I am now trying to make a view that lists out the users contacts. Right now I can’t even get a contact to appear in an ‘alert’ window or anything. Spent 2 days on this so figured I would ask in case anyone can help :smile:
Thanks

call get_contacts() on deviceready event.

function get_contacts() {
    var obj = new ContactFindOptions();
    obj.filter = "";
    obj.multiple = true;
    navigator.contacts.find(["displayName", "name", "phoneNumbers"], contacts_success, contacts_fail, obj);
}
function contacts_success(contacts) {
    debugError("contacts_success(): " +JSON.stringify( contacts));
}
function contacts_fail(msg) {
    debugError("get_contacts() Error: " + msg);
}

Thank you. unfortunately it appears that ionic uses a ‘platform ready’ method instead of device ready. I tried putting this into that area instead and nothing happens at all.

As noted, I used the ionic tabs basic app and am trying to work it in to the app.js (where the platform ready flag is) but nothing happens at all.

I’m sure I am missing something simple or obvious but at present still can’t get this to work.

ignore platform.ready event, create a device ready yourself and then try.

Thanks. Got it working.

Question is, how do I now put that into a function. The moment I move it into a function it doesn’t work anymore.

use a global variable and assign contacts in device ready, use that var in your function. i.e.

$scope.contacts = globalContacts;

how are you guys testing the contact book? obviously you can’t do it in the browser but even on the IOS emulator I can’t seem to get any console.log statements… are there any better tools?

console.log(…) statements output can be seen on xcode log window. You should directly run on real device from xcode and see log window of xcode.

@fox how and where did you placed device ready function? Would be great if you can share snippet.
Thanks

#=================Tutorial================

I wrote a tutorial on how to use ngCordova Contacts plugin to create, find, and delete contacts. You will also find a working example.

##Click here to open a tutorial including working examples

You can use these functions:

$ionicPlatform.ready(function() {	

    $scope.contacts = {};  // We will use it to load contacts 	
	
	
	$scope.contact = {     // We will use it to save a contact

		"displayName": "Gajotres",
		"name": {
			"givenName"  : "Dragan",
			"familyName" : "Gaic",
			"formatted"  : "Dragan Gaic"
		},
		"nickname": 'Gajotres',
		"phoneNumbers": [
			{
				"value": "+385959052082",
				"type": "mobile"
			},
			{
				"value": "+385914600731",
				"type": "phone"
			}				
		],
		"emails": [
			{
				"value": "dragan.gaic@gmail.com",
				"type": "home"
			}
		],
		"addresses": [
			{
				"type": "home",
				"formatted": "Some Address",
				"streetAddress": "Some Address",
				"locality":"Zagreb",
				"region":"Zagreb",
				"postalCode":"10000",
				"country":"Croatia"
			}
		],
		"ims": null,
		"organizations": [
			{
				"type": "Company",
				"name": "Generali",
				"department": "IT",
				"title":"Senior Java Developer"
			}
		],
		"birthday": Date("08/01/1980"),
		"note": "",
		"photos": [
			{
				"value": "https://pbs.twimg.com/profile_images/570169987914924032/pRisI2wr_400x400.jpeg"
			}
		],
		"categories": null,
		"urls": null
	}		
			
    $scope.addContact = function() {
        $cordovaContacts.save($scope.contact).then(function(result) {
            console.log('Contact Saved!');
        }, function(err) {
            console.log('An error has occured while saving contact data!');
        });
    };

    // This function can take some time  so be patient
    $scope.getAllContacts = function() {
        $cordovaContacts.find({filter : 'Robert', fields:  [ 'displayName']}).then(function(allContacts) { //omitting parameter to .find() causes all contacts to be returned
            $scope.contacts = allContacts;
            console.log(JSON.stringify(allContacts));
        });
    };

    $scope.removeContact = function() {
		
		$scope.removeContact = {};   // We will use it to save a contact
		$scope.removeContact.displayName = 'Gajotres'; // Contact Display Name			
		
        $cordovaContacts.remove($scope.removeContact).then(function(result) {
			console.log('Contact Deleted!');
            console.log(JSON.stringify(result));
        }, function(error) {
            console.log('An error has occured while deleting contact data!');
			console.log(JSON.stringify(error));
        });
    }		  

});

Also don’t forget to wrap everything into Ionic ready event.

More complex version can be found in a provided tutorial. Leave me a message if you have more question or if you think something is missing.

1 Like

Thanks gajotres !
if i wish to add more than one filter in getAllContacts() is it possible ?

Hello ionicer,
I made a demo app from example https://blog.nraboy.com/2014/11/create-delete-search-contacts-ionic-framework/.
When I tried to write to native contact
My code:
$cordovaContacts.save({“displayName”: “Steve Jobs”}).then(function(result) {
console.log(“Save successfully”);
}, function(error) {
console.log(error);
});

this error message was displayed when I debugged on Simulator iOS + Safari.
Error: DataCloneError: DOM Exception 25
postMessage@[native code]
iOSExec@http://localhost:12344/cordova.js:981:58
save@http://localhost:12344/plugins/cordova-plugin-contacts/www/Contact.js:173:9
save@http://localhost:12344/lib/ng-cordova.min.js:7:22475
downloadProfile@http://localhost:12344/js/app.js:589:26
fn
http://localhost:12344/lib/ionic/js/ionic.bundle.js:57606:21
$eval@http://localhost:12344/lib/ionic/js/ionic.bundle.js:24678:28
$apply@http://localhost:12344/lib/ionic/js/ionic.bundle.js:24777:28
http://localhost:12344/lib/ionic/js/ionic.bundle.js:57605:19
eventHandler@http://localhost:12344/lib/ionic/js/ionic.bundle.js:12103:25
dispatchEvent@[native code]
triggerMouseEvent@http://localhost:12344/lib/ionic/js/ionic.bundle.js:2870:20
tapClick@http://localhost:12344/lib/ionic/js/ionic.bundle.js:2859:20
tapTouchEnd@http://localhost:12344/lib/ionic/js/ionic.bundle.js:2982:13
Could you please advice this?
Many thanks.

I don’t see any follow to this question. I’m getting the exact same error trying to save. what does DataCloneError: DOM Exception 25 mean? Did this ever get resolved?