iOS/Android Feature Flags

Mobile Feature Flag Resources/Solutions (iOS/Android)

  • LaunchDarkly Mobile iOS Feature Flag SDK – LaunchDarkly
    • An installable feature flag software development kit for iOS apps.  This SDK harnesses the LaunchDarkly app and allows you to target users and manage rollouts.  Feature flags are evaluated in microseconds.
    • iOS SDK GitHub
  • LaunchDarkly Android Feature Flag SDK – LaunchDarkly
    • An installable feature flag software development kit for Android apps.  This SDK harnesses the LaunchDarkly app and allows you to target users and manage rollouts.  Feature flags are evaluated in microseconds.
    • Android SDK GitHub
  • GroundControl for iOS – Mattt Thompson
    • “Many developers don’t realize that they are allowed to remotely control the behavior of their app (provided that the application isn’t downloading any new code). GroundControl gives you a dead-simple way to remotely configure your app, allowing you to add things like feature flags, impromptu A/B tests, or a simple “message of the day”..”
    • GitHub Repo 
  • Android Flagger – Massimiliano Marcon
    • “Flaggr is a library that can be used in Android applications when there is the need for feature flags. Flaggr helps toggling feature flags at runtime.  With Flaggr flags can be specified in a XML resource file and are overridable at runtime when the name starts with _.  Once the library is complete it will also be possible to toggle flags directly from the backend, via GCM or by polling your flags API when the application starts.”
    • GitHub Repo 
  • FeatureKit – Daniel Thrope
    • “FeatureKit is a small Swift framework which is to enable application developers to use feature flags. FeatureKit provides a software framework to support the basics on the client side.”
    • GitHub Repo 
  • toggle – Soham Mondal
    • “A library to add Feature-Toggle capability to your android app.”
    • GitHub Repo
  • ———————

    LaunchDarkly iOS Feature Flag SDK

    Getting started


    If you haven’t taken a look at our Quickstart guide yet, we recommend starting there to see how install our SDK into your iOS application.

    Once the SDK is installed, you’ll want to create a single, shared instance of LDClient, passing in the client configuration object and a user:

     LDConfigBuilder *config = [[LDConfigBuilder alloc] init];
     [config withMobileKey:@"YOUR_MOBILE_KEY"];
        
     LDUserBuilder *user = [[LDUserBuilder alloc] init];
     user = [user withKey:@"aa0ceb"];
        
    [[LDClient sharedInstance] start:config userBuilder:user];
    

    Mobile keys

    Be sure to use a mobile key from your Environments page. Never embed a server-side SDK key into a mobile application.

    Customizing your client


    You can also pass other custom parameters to the client via the configuration object:

    [config withConnectionTimeout:10]; 
    [config withFlushInterval:10];  
    ...
    [[LDClient sharedInstance] start:config userBuilder:user];

    Here, we’ve customized the client connect and flush interval parameters.

    Users


    Feature flag targeting and rollouts are all determined by the user you pass to your client. In our iOS SDK, we use abuilder pattern to make it easy to construct users. Here’s an example:

    LDUserBuilder *user = [[LDUserBuilder alloc] init];
    
    user = [user withKey:"aa0ceb"];
    user = [user withFirstName:"Ernestina"];
    user = [user withLastName:"Evans"];
    user = [user withEmail:"ernestina@example.com"];
    user = [user withCustomArray:"groups" value:groups];

    Let’s walk through this snippet. The first argument to the builder is the user’s key– in this case we’ve used the hash"aa0ceb". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

    All of the other attributes (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes.

    In addition to built-in attributes like names and e-mail addresses, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

    A note on types

    Most of our built-in attributes (like names and e-mail addresses) expect string values. Custom attributes values can be strings, booleans (like true or false), numbers, or lists of strings, booleans or numbers.

    If you enter a custom value on our dashboard that looks like a number or a boolean, it’ll be interpreted that way. The iOS SDK is strongly typed, so be aware of this distinction.

    Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us– organizations, groups, account plans– anything you pass to us becomes available instantly on our dashboard.

    Anonymous users


    You can also distinguish logged-in users from anonymous users in the SDK, as follows:

    LDUserBuilder *user = [[LDUserBuilder alloc] init];
    
    user = [user withKey:"aa0ceb"];
    user = [user withAnonymous:TRUE];

    You will still need to generate a unique key for anonymous users– session IDs or UUIDs work best for this.

    Anonymous users work just like regular users, except that they won’t appear on your Users page in LaunchDarkly. You also can’t search for anonymous users on your Features page, and you can’t search or autocomplete by anonymous user keys. This is actually a good thing– it keeps anonymous users from polluting your Users page!

    Variation


    The variation method determines whether a flag is enabled or not for a specific user. In iOS, there is avariation method for each type (e.g. boolVariation, stringVariation):

    [[LDClient sharedInstance] boolVariation:@"your.feature.key" fallback:FALSE];

    variation calls take the feature flag key, an LDUser, and a fallback value.

    The fallback value will only be returned if an error is encountered– for example, if the feature flag key doesn’t exist or the user doesn’t have a key specified.

    The variation call will automatically create a user in LaunchDarkly if a user with that user key doesn’t exist already. There’s no need to create users ahead of time (but if you do need to, take a look at Identify).

    Handling flag values on initial app launch

    When LDClient is initialized for the first time at app launch, users will receive the feature flag fallback values until polling is completed for the first time.

    You can use the userDidUpdate delegate method to be notified when the feature flag values have been polled and are ready to use (See Realtime UI Updates). Once the flags have been polled for the first time, the SDK will always use the latest stored flag values thereafter.

    Track


    The track method allows you to record actions your users take on your site. This lets you record events that take place on your server. In LaunchDarkly, you can tie these events to goals in A/B tests. You can also attach custom JSON data to your event by passing an extra NSDictionary parameter to track. Here’s a simple example:

     [[LDClient sharedInstance] track:@"Signed up" data:dict];

    Offline mode


    In some situations, you might want to stop making remote calls to LaunchDarkly and switch to fallback values for your feature flags. offline lets you do this easily.

    [[LDClient sharedInstance] offline];
    [[LDClient sharedInstance] boolVariation:@"your.feature.key" fallback:FALSE]; // will always return the fallback value (FALSE)

    You can bring LaunchDarkly back online by calling online.

    Airplane/Flight Mode

    If a user’s device is in airplane/flight mode or if they are not connected to a network, LaunchDarkly will use the latest stored flag settings in memory. If there are no previously stored flag settings, then the fallback values will be used.

    Flush


    Internally, the LaunchDarkly SDK keeps an event buffer for track calls. These are flushed periodically in a background thread. In some situations (for example, if you’re testing out the SDK in a REPL), you may want to manually call flush to process events immediately.

    [[LDClient sharedInstance] flush];

    Note that the flush interval is configurable– if you need to change the interval, you can do so via the configuration.

    Real-Time Updates


    LaunchDarkly manages all flags for a user context in real-time by polling flags based on a real-time event stream. When a flag is modified via the LaunchDarkly dashboard, the flag values for the current user will update almost immediately.

    To accomplish real-time updates, LaunchDarkly broadcasts an event stream that is listened to by the iOS SDK. Whenever an event is performed on the dashboard, the iOS SDK is notified, and then polls for updated flag values.

    To perform real-time updates in your app, your base class will need to conform to the ClientDelegate protocol. The userDidUpdate method of the protocol is called whenever a flag value is changed. If more than one class relies on LaunchDarkly’s feature flags, we recommend you post a notification in this method, in a manner similar to the following:

    - (void)userDidUpdate{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"userUpdatedNotification" object:nil];
    }

    After this, you can add a notification observer to any class that needs to update the app based on the flag values. This observer will point to a selector which can then update your app accordingly.

    Variation methods

    Make sure to use variation methods to get new flag values instead of any locally stored variables.

    Background Fetch


    When the app is backgrounded, the iOS SDK does not receive real-time events. However, there is support for a background fetch to update flag values opportunistically, according to iOS standard defaults.

    To allow background fetch for flags in your app, just add the following code in your AppDelegate:

    -(void)application🙁UIApplication *)application performFetchWithCompletionHandler🙁void (^)(UIBackgroundFetchResult))completionHandler{
        [[NSNotificationCenter defaultCenter] postNotificationName:kLDBackgroundFetchInitiaited object:nil];
    }

    You will also need to enable Background fetch in your Target’s capabilities.

    Changing the User Context


    If your app is used by multiple users on a single device, then you will want to ensure that each user has persistent and personalized flag settings. To achieve this, the SDK will store up to 5 user contexts on a single device, with support for switching between different user contexts.

    You can use the updateUser method to switch user contexts:

    LDUserBuilder *user = [[LDUserBuilder alloc] init];
     user = [user withKey:@"aa0ceb"];
    [[LDClient sharedInstance] updateUser:user];

    ———————

    LaunchDarkly Android Feature Flag SDK

    Android SDK Reference


    This reference guide documents all of the methods available in LaunchDarkly’s Android SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source– head to our Android SDK GitHub repository to look under the hood.

    Getting started


    For the pre-release version of the Android SDK, you’ll need to add the Maven snapshots repository to your project:

    buildscript {
      repositories {
        maven { url "https://oss.sonatype.org/content/groups/public/" }
      }
    }

    Declare a dependency on the Android SDK:

    compile 'com.launchdarkly:launchdarkly-android-client:1.0.0'

    Once the SDK is installed, you’ll want to create a single, shared instance of LDClient, passing in the client configuration object and a user:

    LDConfig ldConfig = new LDConfig.Builder()
        .setMobileKey("YOUR_MOBILE_KEY")
        .build();
    
    user = new LDUser.Builder("user key")
       .email("fake@example.com")
       .build();
    
    ldClient = LDClient.init(this.getApplication(), ldConfig, user, 5);
    

    Client Initialization

    The above example shows the simplest way to create the client. It will block for up to 5 seconds until the latest feature flags have been retrieved from LaunchDarkly. Calling blocking code from the main thread in an Android app is not considered a best practice. Other options are listed below.

    1. Don’t block. The following code will allow you to use the client immediately. Flags from the previous launch of the app are stored on the device.
    ListenableFuture<LDClient> initFuture = LDClient.init(this.getApplication(), ldConfig, user);
    LDClient client = LDClient.get();
    1. Register a listener on the ListenableFuture returned by init() (ensures the very latest feature flags are used):
    ListenableFuture<LDClient> initFuture = LDClient.init(this.getApplication(), ldConfig, user);
    initFuture.addListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String flagValue = LDClient.get().stringVariation("flagKey", "fallback");
                        } catch (LaunchDarklyException e) {
                            e.printStackTrace();
                        }
                    }
                }, Executors.newSingleThreadExecutor());
    

    Mobile keys

    Be sure to use a mobile key from your Environments page. Never embed a server-side SDK key into a mobile application.

    Customizing your client


    You can also pass other custom parameters to the client via the configuration object:

    LDConfig ldConfig = new LDConfig.Builder()
        .setMobileKey("YOUR_MOBILE_KEY")
        .setConnectionTimeoutMillis(5000)
        .setEventsFlushIntervalMillis(5000)
        .build();
    

    Here, we’ve customized the client connect and flush interval parameters.

    Users


    Feature flag targeting and rollouts are all determined by the user you pass to your client. In our Android SDK, we use a builder pattern to make it easy to construct users. Here’s an example:

    user = new LDUser.Builder("aa0ceb")
       .email("fake@example.com")
       .firstName("Jake")
       .lastName("Fake")
       .custom("group", "microsoft")
       .build();

    Let’s walk through this snippet. The first argument to the builder is the user’s key– in this case we’ve used the hash"aa0ceb". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

    All of the other attributes (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes.

    In addition to built-in attributes like names and e-mail addresses, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

    A note on types

    Most of our built-in attributes (like names and e-mail addresses) expect string values. Custom attributes values can be strings, booleans (like true or false), numbers, or lists of strings, booleans or numbers.

    If you enter a custom value on our dashboard that looks like a number or a boolean, it’ll be interpreted that way. The Android SDK is strongly typed, so be aware of this distinction.

    Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us– organizations, groups, account plans– anything you pass to us becomes available instantly on our dashboard.

    Anonymous users


    You can also distinguish logged-in users from anonymous users in the SDK, as follows:

    user = new LDUser.Builder("user key")
       .anonymous(true)
       .build();

    You can leave the key parameter in the Builder null or make it an empty string and the client will automatically set it to a LaunchDarkly-specific device-unique string that is consistent between app restarts and device reboots.

    Anonymous users work just like regular users, except that they won’t appear on your Users page in LaunchDarkly. You also can’t search for anonymous users on your Features page, and you can’t search or autocomplete by anonymous user keys. This is actually a good thing– it keeps anonymous users from polluting your Users page!

    Variation


    The variation method determines whether a flag is enabled or not for a specific user. In Android, there is avariation method for each type (e.g. boolVariation, stringVariation):

    variationResult = ldClient.boolVariation(flagKey, false);

    variation calls take the feature flag key and a fallback value.

    The fallback value will only be returned if an error is encountered– for example, if the feature flag key doesn’t exist or the user doesn’t have a key specified.

    The variation call will automatically create a user in LaunchDarkly if a user with that user key doesn’t exist already. There’s no need to create users ahead of time (but if you do need to, take a look at Identify).

    Handling flag values on initial application launch

    When LDClient is initialized for the first time at app launch, users will receive the feature flag fallback values until an initial connection to LaunchDarkly is completed for the first time. Take a look at the section above on various ways to initialize the client.

    Track


    The track method allows you to record actions your users take on your site. This lets you record events that take place on your server. In LaunchDarkly, you can tie these events to goals in A/B tests. You can also attach custom JSON data to your event by passing an extra JsonElement parameter to track. Here’s a simple example:

    ldclient.track("custom event", data)

    Offline mode


    In some situations, you might want to stop making remote calls to LaunchDarkly and switch to the last known values for your feature flags. offline mode lets you do this easily.

    LDConfig ldConfig = new LDConfig.Builder()
        .setMobileKey("YOUR_MOBILE_KEY")
        .setOffline(true)
        .build();
    
    ldClient = LDClient.init(this.getApplication(), ldConfig, user);
    
    // Or to switch an already-instantiated client to offline mode:
    ldclient.setOffline()

    Airplane/Flight Mode

    If a user’s device is in airplane/flight mode or if they are not connected to a network, LaunchDarkly will use the latest stored flag settings in memory. If there are no previously stored flag settings, then the fallback values will be used.

    Flush


    Internally, the LaunchDarkly SDK keeps an event buffer for track calls. These are flushed periodically in a background thread. In some situations (for example, if you’re testing out the SDK in a simulator), you may want to manually call flush to process events immediately.

    ldclient.flush()

    Note that the flush interval is configurable– if you need to change the interval, you can do so via the configuration.

    Changing the User Context


    If your app is used by multiple users on a single device, you may want to change users and have separate flag settings for each user. To achieve this, the SDK will store the last 5 user contexts on a single device, with support for switching between different user contexts.

    You can use the identify method to switch user contexts:

    LDUser updatedUser = new LDUser.Builder(user)
       .email("fake2@example.com")
       .build();
    
    ldClient.identify(user);

    The identify() call will load any saved flag values for the new user and immediately trigger an update of the latest flags from LaunchDarkly.

    Identify() returns a ListenableFuture. If you want to be sure subsequent code is using the latest values from the server, you can register a listener with the future.

    Real-Time Updates


    LaunchDarkly manages all flags for a user context in real-time by polling flags based on a real-time event stream. When a flag is modified via the LaunchDarkly dashboard, the flag values for the current user will update almost immediately.

    To accomplish real-time updates, LaunchDarkly broadcasts an event stream that is listened to by the Android SDK. Whenever an event is performed on the dashboard, the Android SDK is notified, and then polls for updated flag values.

    To perform real-time updates in your app, your app will need to register listeners for each flag you’d like to watch:

    String flagKey = "yourFlagKey";
    
    FeatureFlagChangeListener listener = new FeatureFlagChangeListener() {
      @Override
      public void onFeatureFlagChange(String flagKey) {
        bool newValue = newLDClient.get().boolVariation(flagKey, false);
      }
    }
    
    LDClient.get().registerFeatureFlagListener(flagKey, listener);

    Similarly you can unregister listeners to disable them:

    LDClient.get().unregisterFeatureFlagListener(flagKey, listener);

    Background Fetch


    When the app is backgrounded, the Android SDK does not receive real-time events. However, a battery-consciousAndroid Alarm is set to poll for updates once every 5 minutes. This periodic polling only happens after the app has been run once since device boot.

    Troubleshooting


    The Android SDK makes heavy use of the built-in Android logging capabilities. You won’t see much at the Info level, but turn on Debug logging for very descriptive output.