Persist data on a mobile device even if the app is uninstalled - using Ionic and Cordova
23 Apr 2015There are many options to store data in cordova apps such as local storage, sqlite or the file system. However when the user uninstalls the app, this data is removed as well (besides the file systems plugin on Android, more details below). I was looking for a way to store data that would persist even if the app is uninstalled and then re-installed again. Preferably with the same API that I could use on both platforms.
The reason such functionality would be useful is for cases when you would like to let the user use the app as soon as he opens it without requiring him to login or signup, but you would also like to give him the option to keep his data if he chooses to reinstall the app for some reason. Another use case is if you give away points or credits to first time users but would like to prevent them from deleting and downloading your app to keep getting the same promotion again.
ng-persist
ng-persist provides a consistent API for both Android and iOS but under the hood, works in a different way for each platform.
On iOS, it uses the keychain that persists the data even if the app is uninstalled.
On Android, it stores data on the external storage SD Card using the file plugin in the
cordova.file.externalRootDirectory
directory. This data will not be removed if the app is
uninstalled.
Usage
Install ng-cordova (and the ngsotrage library that it uses) using bower:
$ bower install ng-persist ngstorage --save
Add the cordova plugins mentioned above:
$ cordova plugin add https://github.com/shazron/KeychainPlugin.git
and
$ cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git
Require the modules in your app:
angular.module('myApp', [
'ngStorage',
'ng-persist'
]);
Store data in the following way:
$persist
.set(namespace, key, val)
.then(function () {
// saved
});
Try to remove the app from the device and install it again, then try to read what you saved:
$persist
.get(namespace, key, fallback)
.then(function (val) {
// val is either the value, if exists, or the fallback
});
Remove data from the device:
$persist
.remove(namespace, key)
.then(function () {
// removed
});
ng-persist will also work in the browser and fallback on local storage to make testing easier.
Alternative method - if your app uses an API
The UniqueDeviceID plugin is a good alternative if you would like to identify the user with a unique ID that you would send to your api. Besides iOS and Android it also supports Windows Phone 8.
This plugin generates a unique id on Android and Windows, that remains the same per device even if the app is uninstalled. On iOS, where it is not possible to generate such an id, it will generate a random id and store it to the iOS keychain.