in Angular, Ionic

How to get a persistent unique device ID in Ionic for iOS

Simple way to store uuid as device.uuid. Using the Native cordova device plugin gives inconsistent results in iOS. Not only this it changes every time the app is installed. Might be a rare case for some but in the app i’m building we use it to lockdown which devices can use the app irrespective of login credentials.

I used this in conjunction with the hashids library. And you will need to follow the instructions to include the KeyChain plugin and ionic library.

validateUuid() {
    let date = new Date();
    let components = [
        date.getFullYear(),
        date.getMonth(),
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
    ];

    let id = components.join("");
    let hashids = new Hashids();
    let newKey = hashids.encode(id).toUpperCase();

        return new Promise((resolve,reject) => {
            if(window.cordova) {
                this.keychain.get('APP_NAMESPACE_KEY').then((uuid) => {
                    if (!uuid) {
                          this.keychain.set('APP_NAMESPACE_KEY', newKey, false).then(() => {
                              this.appService.set('deviceId',newKey);
                              return resolve();
                          }).catch((err) => {
                              return resolve();
                          });

                      } else {
                          this.appService.set('deviceId', val);
                          return resolve();
                      }
                }).catch(() => {
                    //something went wrong
                    return resolve();

                });
            } else {
                this.appService.set('deviceId','browser-id');
                return resolve();
            }
        }).then(() => {
            if(this.platform.is('android')) {
                this.appService.set('deviceId',window.device.uuid);
            }
        });
}

Here our validateUuid function returns a promise, first we generate a new hash in case we need it later, then first check if the keychain value exists (APP_NAMESPACE_KEY). If it does return that value, or create it.

We also do a check if running in the browser by checking for window.cordova or not, if not returning a default “browser-id”.

In my app I have an appService that sets/gets the value of the deviceId which is used elsewhere around the app.

Finally if running on Android then simply set it to window.device.uuid as Android does not currently change this each time.

 

Write a Comment

Comment

  1. Hey can it ever happen that you push multiple IDS for same device ? And how to tackle the issue? Like in some case if same device saves multiple device IDS, we are having trouble. Although we have handled the issue in sign in to remove keychain from device. And create new on enter.