问题
I have feature in my app that checks users contacts using cordova contacts plugin with an online database of users. If the any of the contacts in the users device have accounts the data from the account is updated on the device.
The function works with things like name and date of birth but emails and phone numbers don't overwrite the existing contact data it instead creates new entry for these.
This particular user should only have 1 email address and 1 phone number.
JSON reponse and save
var contacts = json.contacts;
for(var x = 0; x < contacts.length; x++){
var user = contacts[x];
//console.log(user);
//get old contact by id
//Set the options for finding conact
var options = new ContactFindOptions();
options.filter = user.id; //name that you want to search
options.multiple = false;
var fields = ["id","displayName"];
navigator.contacts.find(fields, function(c){
c = c[0];
var dob = user.iceTV.dob.split(':');
c.displayName = user.iceTV.f_name + " " + user.iceTV.l_name;
c.nickname = user.iceTV.f_name + " " + user.iceTV.l_name;
c.birthday = new Date(dob[2], dob[1] - 1, dob[0]);
c.name.givenName = user.iceTV.f_name;
c.name.familyName = user.iceTV.l_name;
c.name.formatted = user.iceTV.f_name + " " + user.iceTV.l_name;
if(c.emails == null){
c.emails = [];
}
for(var a = 0; a < user.emails; a++){
c.emails[a] = { value : user.emails[a] };
}
if(c.phoneNumbers == null){
c.phoneNumbers = [];
}
c.phoneNumbers[0] = {type : 'mobile', value: user.iceTV.number};
if(user.pp == null){
c.photos = null;
} else {
contacts.photos[0] = {
pref : false,
type : 'url',
value : user.iceTV.pp
};
}
c.save(function(saveSuccess) {
console.log('User updated' ,c);
}, function(saveError){
console.log("Error when updating");
});
}, function (e){
makeToast("Error = " + e.code);
}, options);
}
回答1:
I had the same issue and fixed it by adding an id to the phone numbers. For your example code the line you'd have to change would look like this:
c.phoneNumbers[0] = {type : 'mobile', value: user.iceTV.number, id: 0};
But: This only fixes the duplication. When you remove a phoneNumber in the database, it won't be removed in the contact. See my question here for further details.
来源:https://stackoverflow.com/questions/35698798/cordova-contacts-plugin-contact-data-is-duplicating-instead-of-overwriting-conta