🐦 Grab your early bird tickets for the next NativeScript conference! jsMobileConf is coming back to Boston.

NativeScript Core

Application Settings

The Application Settings module is used to store strings, booleans and numbers in built-in key/value store. The module uses SharedPreferences on Android and NSUserDefaults on iOS. The application-settings is suitable for tasks like saving and retriving small portions of custom values from the device’s local storage. Storing to local storage means that you can reuse the key-value pairs after the application is restarted (e.g. remember if a user has logged in orsave user UI preferences).

The application settings module is required from tns-core-modules/application-settings.

const appSettings = require("application-settings");
import * as appSettings from "tns-core-modules/application-settings";

Basics

Get and Set Boolean

Set and get a boolean value and provide default value in case it is not set.

const items = [];
appSettings.setBoolean("isTurnedOn", true);
const isTurnedOn = appSettings.getBoolean("isTurnedOn", false);
const items = [];
appSettings.setBoolean("isTurnedOn", true);
const isTurnedOn = appSettings.getBoolean("isTurnedOn", false);

Get and Set String

Set and get a string value.

appSettings.setString("username", "NickIliev");
const username = appSettings.getString("username");
appSettings.setString("username", "NickIliev");
const username = appSettings.getString("username");

Get and Set Number

Set and get a numeric value.

appSettings.setNumber("locationX", 54.321);
const locationX = parseFloat(appSettings.getNumber("locationX").toFixed(3));

// Note: The MIN & MAX number ranges are limited by the JavaScript number implementation - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
// On Android, the native method is also setting java.lang.Float which might lead to approximations during the conversion.
// For really large numbers (e.g. like the value from getDate()) use setString and save the values as strings.
appSettings.setNumber("locationX", 54.321);
const locX = appSettings.getNumber("locationX").toFixed(3);

// Note: The MIN & MAX number ranges are limited by the JavaScript number implementation
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
// On Android, the native method is also setting java.lang.Float which leads to approximations during conversion.
// For really large numbers (e.g. like the value from getDate()) use setString and save the values as strings.

Key Check

Checking for existence of specific key.

// will return false if there is no "noBoolKey"
const noBoolKey = appSettings.hasKey("noBoolKey");
// will return false if there is no "noBoolKey"
const noBoolKey = appSettings.hasKey("noBoolKey");

Delete a Value

Removes a value (if existing) for a key.

// will remove the setting for a key
appSettings.remove("keyToRemove");

Delete All Values

Removes all values from the application settings.

// Removes all values.
appSettings.clear();
// Removes all values.
appSettings.clear();

Default Values

Reading values that are not set before, while providing default value.

// will return "No string value" if there is no value for "noSuchKey"
const someKey = appSettings.getString("noSuchKey", "No string value");
// will return "No string value" if there is no value for "noSuchKey"
const someKey = appSettings.getString("noSuchKey", "No string value");

Reading values that are not set before not providing default value.

// will return undefined if there is no value for "noSuchKey"
const defaultValue = appSettings.getString("noSuchKey");
// will return undefined if there is no value for "noSuchKey"
const defaultValue = appSettings.getString("noSuchKey");

Improve this document

Demo Source


Native Access

One of the main advantages of NativeScript is the direct access to the native APIs for both Android and iOS. The application-module functionality can be extended with native logic just as every other module and widget in NativeScript. The below example demonstrates how to access all stored keys using the native APIs on Android and iOS.

const getNativeApplication = require("application").getNativeApplication;
const platformModule = require("platform");
const utils = require("utils/utils");

function getAll() {
    if (platformModule.isAndroid) {
        const sharedPreferences = getNativeApplication().getApplicationContext().getSharedPreferences("prefs.db", 0);
        const mappedPreferences = sharedPreferences.getAll();
        const iterator = mappedPreferences.keySet().iterator();

        while (iterator.hasNext()) {
            const key = iterator.next();
            console.log(key); // myString, myNumbver, isReal
            const value = mappedPreferences.get(key);
            console.log(value); // "John Doe", 42, true
        }

    } else if (platformModule.isIOS) {
        // Note: If using TypeScript you will need tns-platform-declarations plugin to access the native APIs like NSUserDefaults
        const userDefaults = utils.ios.getter(NSUserDefaults, NSUserDefaults.standardUserDefaults);
        const dictionaryUserDefaults = userDefaults.dictionaryRepresentation();

        const allKeys = dictionaryUserDefaults.allKeys;
        console.log(allKeys);
        const allValues = dictionaryUserDefaults.allValues;
        console.log(allValues);
    }
}
import { getNativeApplication } from "tns-core-modules/application";
import { isAndroid, isIOS } from "tns-core-modules/platform";
import * as utils from "tns-core-modules/utils/utils";

export function getAll() {
    if (isAndroid) {
        const sharedPreferences = getNativeApplication().getApplicationContext().getSharedPreferences("prefs.db", 0);
        const mappedPreferences = sharedPreferences.getAll();
        const iterator = mappedPreferences.keySet().iterator();

        while (iterator.hasNext()) {
            const key = iterator.next();
            console.log(key); // myString, myNumbver, isReal
            const value = mappedPreferences.get(key);
            console.log(value); // "John Doe", 42, true
        }

    } else if (isIOS) {
        // tslint:disable-next-line
        // Note: If using TypeScript you will need tns-platform-declarations plugin to access the native APIs like NSUserDefaults
        const userDefaults = utils.ios.getter(NSUserDefaults, NSUserDefaults.standardUserDefaults);
        const dictionaryUserDefaults = userDefaults.dictionaryRepresentation();

        const allKeys = dictionaryUserDefaults.allKeys;
        console.log(allKeys);
        const allValues = dictionaryUserDefaults.allValues;
        console.log(allValues);
    }
}

Improve this document

Demo Source


Native Component

Android iOS
android.content.SharedPreferences NSUserDefaults