Variable Implementation

Guide for implementing variables by supported SDK

The below guide is meant to help you understand and get your variables up and running quickly. Each of the platforms Leanplum supports for variables are below. Click to be guided to the platform you are using.

Select your OS or language below for specific instructions on setup.

More on Variables Implementation for iOS.

More on Variables Implementation for Android.

More on setup for Unity Variables Implementation.

More on Variables Implementation using our JavaScript SDK.

More on Variables Implementation for React Native.

iOS Variables

In a variables implementation for iOS, it's important to define all of your variables before calling Leanplum.start(). To group variables on the dashboard, you will need to use periods. There are differences for how variables are handled depending the native iOS language you use.

Defining variables

Swift

A Swift implementation of Leanplum variables does not support macros like Objective-C does. Instead, we use a Var class directly for when variables are defined. This means you will need to define variables using the Var class. If you are wanting to group variables together, this method requires you use dots in the name of the variable to group values into a structured way. See Modeling structured data for examples.

With Swift, you must define all of your Leanplum variables before calling Leanplum.start. In order to access a variable in another controller or file, you will need to define the variable again; the first time before start, which will set the value, with subsequent calls will returning the cached value.

Note: Be careful where you place the Var calls to ensure the first call is truly called first.

//Define the variable and set the name and value using the Var class. 
//To access the value in your code, use the floatValue method.

let welcomeMsg = Var(name: "startLabel", string: "Start") // Label of the "Start" button
let showAds = Var(name: "showAds", boolean: false) // Whether or not to show ads in the app.
let shootSpeed = Var(name: "shootSpeed", float: 1.0) // How fast your ship shoots.
let myColor = Var(name: "myColor", color: UIColor.gray)
let goldStar = Var(name: "goldStar", file: "gold_star.png") // Location of Gold Star image file.

let powerUp = Var(name: "powerUp", dictionary: [
  "name": "Turbo Boost",
  "price": 150,
  "speedMultiplier": 1.5,
  "timeout": 15])

Objective-C

To implement Leanplum variables with Objective-C, you will need to define variables outside of your methods, like you would a constant, using our DEFINE_VAR macros. We recommend using underscores in the variable name to group values into a structured variable. We have examples for structuring data in our article Modeling structured data.

In the below example, however, we define Variables both in the AppDelegate.m and in ViewController.m using the DEFINE_VAR macros to define different kind of variables. In this case, these are String, Boolean, float, int, a dictionary, and a file.

In the AppDelegate.m:

DEFINE_VAR_STRING(welcomeMessage, @"Welcome to Leanplum!");
DEFINE_VAR_BOOL(showAds, false);
DEFINE_VAR_FLOAT(floatvar, 1.5);
DEFINE_VAR_INT(intvalue, 20);

DEFINE_VAR_DICTIONARY_WITH_OBJECTS_AND_KEYS(
                                            powerup,
                                            @"Turbo Boost", @"name",
                                            @150, @"price",
                                            @1.5, @"speedMultiplier",
                                            @15, @"timeout",
                                            nil);

In another class like ViewController.m, would look like:

DEFINE_VAR_FILE(LPsquarelogo, @"leanplum-squarelogo.png");

When your app launches in Development mode with a registered test device, all the Variables that you define in the project by using the DEFINE_VAR macros are synchronized and be added to the Dashboard.

Using Callbacks

When the app starts, the SDK retrieves Variable data asynchronously. To use the latest values of the variables, use Variables inside Leanplum callbacks. See more on Callbacks

Following the sample project code, once the app starts, callbacks are triggered based on when variables values are changed. In this case, their values are printed in the console:

Leanplum.onVariablesChanged {
	print(self.welcomeLabel.titleLabel.text = self.welcomeMsg.stringValue)
  print(showAds.boolValue())
  print(shootSpeed.floatValue())
  print(myColor.colorValue())
  print(self.LPlogo.image = goldStar.imageValue())
  
  self.speed = (powerUp?.object(forKey: "speedMultiplier") as! NSNumber).floatValue
}
[Leanplum onVariablesChanged:^{
        NSLog(@"%@", welcomeMessage.stringValue);
        NSLog(@" %s", showAds.boolValue ? "true" : "false");
        NSLog(@"%0.1f", floatvar.floatValue);
        NSLog(@"%d", intvalue.intValue);
        NSLog(@"%2f", [[powerup objectForKey:@"speedMultiplier"] floatValue]);
    }];

Note: In the case of variable files, the callback will be slightly different and triggered when the file is downloaded from the server. See below for example.

Leanplum.onVariablesChangedAndNoDownloadsPending {
       LPlogo.image = LPsquarelogo.imageValue
  }
[Leanplum onVariablesChangedAndNoDownloadsPending:^{
        LPlogo.image = LPsquarelogo.imageValue;
    }];

Android Variables

In a variables implementation for Android, it's important to define all of your variables before calling Leanplum.start(). Below are the ways you can define variables in Android and then use callbacks.

Defining Variables

There are two ways to define variables in your Android Project

1. Using @Variable annotation

Using the @Variable annotation on public static class members is the easiest and most convenient way to define variables. See below for an example.

public class MainActivity extends LeanplumActivity {
    @Variable public static String welcomeLabel = "Welcome!";
    ...
}

You can use this method to define variables:

  • Inside your Application class if it extends LeanplumApplication.
  • In your main activity if it extends one of the LeanplumActivity classes and calls Leanplum.start.
  • In another class. Use the Parser class to detect the annotations before calling Leanplum.start.

If you choose to define variables in an Activity or Class that does make your start call, you will need to use Parser.parseVariablesForClasses to collect these variable definitions before your start call.

For example, if we have variables defined in ClassA and ClassB, we need to add the following to our ApplicationClass before start:

...
import com.leanplum.annotations.Parser;
...
public class ApplicationClass extends LeanplumApplication {

  @Override
  public void onCreate() {
    super.onCreate();
    Leanplum.setApplicationContext(this);
    ...
    // Parse variables from other classes.
    Parser.parseVariablesForClasses(ClassA.class, ClassB.class);
    // Then, call start.
    Leanplum.start();
  }

}

If you define your variables in an ApplicationClass or Activity where you call start, and the class does not extend LeanplumApplication or LeanplumActivity, then you must use the Parser class to detect that class's variable annotations.

...
import com.leanplum.annotations.Parser;
...
public class ApplicationClass extends Application {

  @Variable
  public static String welcome = "Hi there!";

  @Override
  public void onCreate() {
    super.onCreate();
    Leanplum.setApplicationContext(this);
    ...
    // Parse variables from this class.
    Parser.parseVariables(this);
    // Then, call start.
    Leanplum.start();
  }

}

2. Using Var.define

If you are going to use Var.define, a few items you will need to consider.

  • Anywhere in your Class before starting Leanplum.
  • In another class outside of the onCreate() method. Use also in this case the Parser class to detect the variable before calling Leanplum.start
public class MainActivity extends LeanplumActivity {
    public static Var<String> welcomeLabel = Var.define("welcomeLabel", "Welcome!");
  ...
}

In this sample, we define different variables in different Activities and in the Application class as well.

When the App starts, the code is executed in the Application class, as well as in the MainActivity. The Variables defined in the other classes are being parsed inside the onCreate() method before Leanplum.start executes.

You must define variables with this method before calling Leanplum.start.

In the sample, we start Leanplum in the Application class, which is also not extending a LeanplumApplication class but we are implementing the Session Lifecycle manually.

@Override
public void onCreate() {
    super.onCreate();
    Leanplum.setApplicationContext(this);
    Parser.parseVariables(this);
    Parser.parseVariablesForClasses(AnotherActivity.class, AnotherLPactivity.class);
    LeanplumActivityHelper.enableLifecycleCallbacks(this);
}

Using Callbacks

Once the Variables are synchronized, they trigger callbacks to notify the application. You can place callbacks where you need to use the Variable values.

In the project sample code, we are printing out the Variable values defined in the Application class.

So, for example, in the Application class:

Leanplum.addVariablesChangedHandler(new VariablesChangedCallback() {
    @Override
    public void variablesChanged() {

        Log.i("#### ", welcomeLabel.value());

        for (Map.Entry<String, Object> entry : powerup.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            Log.i("#### ", "Application class var : " + key + " " + value.toString());
        }
    }
});

In the MainActivity class (accessing the Variables defined in the Application class):

Leanplum.addVariablesChangedHandler(new VariablesChangedCallback() {
    @Override
    public void variablesChanged() {
        welcomeMessageText1.setText(ApplicationClass.String_Welcome1);
        welcomeMessageText2.setText(ApplicationClass.String_Welcome2);
    }
});

Note: For images, make sure that the image value is used after it has been downloaded.

Leanplum.addVariablesChangedAndNoDownloadsPendingHandler()

Unity Variables

It's important to define all of your variables before calling Leanplum.Start. Use periods to group variables on the dashboard. Below is an example of how you can set variables in the Unity Editor for quicker development time. Otherwise, refer to the iOS and Android variable guides to handle variables when you export your project

Var<string> varText = Var.Define("var_text", "Default value in code");
Var<int> varInt = Var.Define("var_int", 1);
Var<bool> varBool = Var.Define("var_bool", false);
Var<double> varDouble = Var.Define("var_double", 5.0);

JavaScript Variables

In a variables implementation for JavaScript, it's important to define all of your variables before calling Leanplum.start(). Below are the ways you can define variables in your JavaScript application and then use callbacks.

Defining Variables

To define the Variable defaults, you can use the setVariables method. Nested objects become dictionaries in the Leanplum dashboard

Leanplum.setVariables({
  StoreTitle: "Powerup Store",
  Items: [
    {
      name: "Speed Boost",
      price: 100
    }, {
      name: "Health Boost",
      price: 150
    }
  ]
});

Using callbacks

Variable values are fetched asynchronously from the Leanplum servers. To use the latest values, get the Variable values through a callback. This also ensures proper handling during development and when you fetch variable values through forceContentUpdate calls.

//Gets a particular variable.
var title = Leanplum.getVariable('StoreTitle');
var speedBoost = Leanplum.getVariable('Items', 0);
var healthBoostName = Leanplum.getVariable('Items', 1, 'name');

//Gets multiple variables
Leanplum.addVariablesChangedHandler(function() {
    var variables = Leanplum.getVariables();
    document.querySelector("#welcomeMessage").innerText = variables.welcomeMessage;
})

To resolve a file variable filename to a path, call the getFileUrl method, available in SDK versions 1.7.0 and later.

var filename = Leanplum.getVariable('SplashImage');
var url = Leanplum.getFileUrl(filename);

React Native Variables

In a variables implementation for React Native, it's important to define all of your variables before calling Leanplum.start(). Below are the ways you can define variables in your React Native application and then use callbacks.

Define Variables

Below using the setVariables method will define the variable on the Leanplum side and once synced, show on the Leanplum dashboard

Leanplum.setVariables({
  stringVar: 'Some string variable',
  numVar: 1,
  boolVar: true,
  mapVar: {
    stringVal: 'some string val',
    'numVal:': 5,
  },
  listVar: [1, 2, 3],
});

// Example
Leanplum.setVariables({
  title: "Welcome",
  isFeatureEnabled: true,
  gameOptions: {
    speed: 60,
    price: 100
  }
});

Setting an asset:

Leanplum.setVariableAsset(ASSET_VARIABLE_NAME, path, (newPath: string) => {
  // handle image 
});

Using Callbacks

The below methods are callbacks you can use to grab the variable value.

Get variables will return all variables that were set by setVariables() before calling start method.

Leanplum.getVariables();

Get variable with name will return only variable that was set by setVariables() before calling start method.

Leanplum.getVariables("stringVar");
// Example
Leanplum.getVariables("isFeatureEnabled");

Get asset:

Leanplum.getVariableAsset(ASSET_VARIABLE_NAME);

📘

Note

It is recommended to define the variables only in one place inside your project.