How to use Feature Flags in an iOS App [with code examples]

By Ben Rometsch on November 15, 2021
iOS Illustration

A feature flag helps you to enable or disable functionality remotely without deploying code. This is extremely helpful if you want to test and deploy new features without sending an App Store update. This enables you to decouple deployment from release, and you can experiment over the entire lifecycle of features.

Flagsmith provides you with an all-in-one platform for developing, implementing, and managing your feature flags. Whether you are moving off an in-house solution or using toggles for the first time, you will be amazed by the power and efficiency gained by using Flagsmith. You can manage feature flags by the development environment, and a segment of users or a percentage for individual users. This means quickly implementing practices like canary deployments.

This article will explore how to use a feature flag in an iOS App. It contains the following:

  • Creating Feature Flag on Flagsmith
  • Installing the Flagsmith iOS SDK
  • Working with the Flagsmith iOS SDK
  • Testing the Feature Flag
  • Testing Different Environments

So let’s get started!

Getting Started

Flagsmith has a sample project to showcase a demo feature flag, and you can download the starter project from here. This article assumes you know the basics of iOS development.

Head over to Flagsmith and click Sign In on the top right corner. If you’re new to Flagsmith, you can start on the free trial:

Flagsmith.com page for login or signup

You can sign up via GitHub, Google or email:

Flagsmith sign up flow

Then, create an organization to house all your projects:

Flagsmith create organization onboarding flow

After creating the organization, create the project that will contain the feature flags. When you create a project, Flagsmith also generates a development and production environment for you. You can create features for your project, then enable and configure them per environment.

Flagsmith create project onboarding flow

You’ll be redirected to your project’s homepage that will contain all the information about your features:

Flagsmith application homepage

Now that you’ve set up the project, it’s time to create your first feature flag!

Creating a Feature Flag on Flagsmith

To create your first feature, head over to the Features tab from the sidebar. You’ll be taken to the Features main page:

Flagsmith application - create your first feature

There are two types of features that you can create for your project:

  • Feature Flags: This allows you to toggle features on and off. For example, a messaging feature on your app that you only want to show and test in Development.
  • Remote configuration: This allows you to provide configuration for a particular feature. For example, anything from font size for a website/mobile app or an environment variable for a server.

In this article, we’ll focus on adding a feature flag. Every feature comes with two default environments:

  • Development
  • Production

When you create a new feature, Flagsmith makes copies of it for each environment, allowing you to edit the values in the feature separately. Also, you can create more environments if you want.

The Flagsmith SDK also provides you with the ability to identify your user when they log in to your app. It adds them to the user’s page. You can then configure the features per user. For example, while working on a new messaging feature, you can show it to only a particular identified user or set of users.

On the Features page, click on the Create Your First Feature button. It slides a New Feature page, where you can fill in the details:

Creating a feature in the Flagsmith application

There are five options for every feature:

  • ID: Name of the feature. For example, header_size.
  • Enabled by default: A switch to enable the feature by default.
  • Value: providing an optional value with the feature in the form of .txt.json.xmltoml and .yaml.
  • Description: Provide an optional note that explains the feature. For example, “This determines what size the header is”.
  • Archived: A switch to archive a feature. It helps you filter a feature from the Flagsmith dashboard to determine the ones that are not relevant anymore.

For example, you can name the ID as show_onboarding for a feature flag to enable the onboarding screen. It will be disabled by default. Let’s leave the Value field empty as it will act as a feature flag with only a boolean value. Then, add the description as This enables the onboarding screen. As you’re going to use it, leave the Archived option off.

Note that this creates the feature for all environments, and you can edit this feature for every environment after the feature is created.

After you’re done filling in the information, click the Create Feature button. And that’s it, you’ve created your first feature flag within a few minutes!

Installing the Flagsmith iOS SDK

Flagsmith iOS SDK can be installed via two ways:

  • CocoaPods
  • Swift Package Manager (SPM)

To install via CocoaPods, add the following line to your pod file:

pod 'FlagsmithClient', '~> 1.0.1'

To install via SPM, add the following to your Package.swift file:

dependencies: [
    .package(url: "https://github.com/Flagsmith/flagsmith-ios-client.git", from: "1.1.1"),
]

If your project doesn’t contain a Package.swift file, go to the Menu bar in Xcode, select File, and then Add Packages. Then, in the search field, add the following URL:

https://github.com/Flagsmith/flagsmith-ios-client.git

Click Next. The current version at the time of writing is 1.1.1. Click Next again and then checkmark the SDK to add to your project’s target. Finally, click Finish to add the iOS SDK to your project.

Working with the Flagsmith iOS SDK

If you’re using AppDelegate, you can initialize the SDK in application(_:didFinishLaunchingWithOptions:) method:

1import FlagsmithClient
2
3func application(_ application: UIApplication,
4 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
5  Flagsmith.shared.apiKey = "<#YOUR API KEY#>"
6}

If you’re using SwiftUI’s new lifecycle, it can be initialized by setting the API key inside the init() method in the App. In the sample project, it can be initialized as follows:

1import FlagsmithClient
2
3extension FlagsmithExampleApp {
4  private func initializeFlagsmith() {
5    Flagsmith.shared.apiKey = "<#YOUR API KEY#>"
6  }
7}
8

Now, in the FlagsmithExampleApp struct, you call this method in the init():

1@main
2struct FlagsmithExampleApp: App {
3
4  init() {
5    initializeFlagsmith()
6  }
7
8  var body: some Scene {
9    WindowGroup {
10      MainView()
11    }
12  }
13}

By setting up your API key and initializing the SDK at launch, you can fetch the feature flags from Flagsmith.

The SDK offers two methods to retrieve the flags – you can either fetch all the flags or retrieve the flag by its name.

For the former one, you then loop over the flags and save them accordingly:

1Flagsmith.shared.getFeatureFlags() { (result) in
2    switch result {
3    case .success(let flags):
4        for flag in flags {
5            let name = flag.feature.name
6            let value = flag.value?.stringValue
7            let enabled = flag.enabled
8            print(name, "= enabled:", enabled, "value:", value ?? "nil")
9        }
10    case .failure(let error):
11        print(error)
12    }
13}

In the sample project, you can create an enum for the feature flags:

1enum FeatureFlags: String {
2  case showOnboarding = "show_onboarding"
3
4  var id: String {
5    self.rawValue
6  }
7}
8

Use the case to get the desired feature flag. Then, put this piece of code in the initialization method to retrieve the flags at launch:

1private func initializeFlagsmith() {
2  Flagsmith.shared.apiKey = "<#YOUR API KEY#>"
3
4  Flagsmith.shared.getFeatureFlags { (result) in
5    switch result {
6      case .success(let flags):
7        for flag in flags {
8          // Comparing the feature flag's name to the particular ID.
9          if flag.feature.name == FeatureFlags.showOnboarding.id {
10            DispatchQueue.main.async {
11              viewModel.showOnboarding = flag.enabled
12            }
13          }
14        }
15      case .failure(let error):
16        print(error)
17    }
18  }
19}
20

Alternatively, you can search for feature flag by its name. It returns a Result<Bool, Error>:

1Flagsmith.shared
2  .hasFeatureFlag(withID: FeatureFlags.showOnboarding.id, forIdentity: nil) { (result) in
3  switch result {
4    case .success(let value):
5      DispatchQueue.main.async {
6        viewModel.showOnboarding = value
7     }
8    case .failure(let error):
9      print(error)
10  }
11}

In the beginning, the value of the flag show_onboarding was set to false by default. Run the app, and you’ll see that it opens to the main screen instead of the onboarding screen.

iOS app showing main screen

In the next section, you’re going to test the feature by toggling the value of the feature flag and running the app accordingly.

Testing the Feature Flag

Go to the Flagsmith project and toggle the feature flag show_onboarding by switching the OFF button to ON.

Flagsmith application - toggling feature flag from OFF to ON

It will show an alert that will turn show onboarding “On” for Development. Click on Confirm Changes.

Flagsmith application - confirming change of toggling feature flag from OFF to ON

You’ve successfully changed the value of the feature flag.

Flagsmith application - showing the feature flag as ON

Now, head over to Xcode, and rerun the project. You’ll see that the onboarding screen is being displayed as the first screen!

iOS app showing onboarding screen

Testing Different Environments

Flagsmith also provides you with different environments per feature. You can find the different environment on the main page of the project:

Flagsmith application - Production environment

Each environment has its own specific API key. So, from the sidebar, select Settings under the Production heading and copy the API key from here. show_onboarding is disabled by default in Production, while in the previous section, you enabled it in Development.

To differentiate between the two, go back to Xcode and FlagsmithExampleApp.swift. Replace the following code where you set the API key with:

1#if DEBUG
2    Flagsmith.shared.apiKey = "<#YOUR DEVELOPMENT API KEY#>"
3#else
4    Flagsmith.shared.apiKey = "<#YOUR PRODUCTION API KEY#>"
5#endif

Now, click on the current scheme and then edit the scheme:

Xcode &quot;Edit Scheme&quot; menu

From the sidebar, select Run. Under the Info tab, change the build configuration to Release:

Xcode showing Build Configuration as &quot;Release&quot;

Run the app, and you’ll see that the onboarding is disabled!

iOS app showing main screen

If you run the app in Debug configuration, you will see the onboarding screen again. You can create a custom build configuration on Xcode as well. For example, you can create an Environment Test Flight in Flagsmith and create a similar one in Xcode.

Conclusion

You can download the final project from here. Using Flagsmith, you can release features with confidence and manage feature flags across web, mobile, and server-side applications.

This article helps you get started with using Feature Flags in your iOS app so that you have more control over your features without worrying about sending updates. You can use the best open-source feature flag for your next Xcode project. Flagsmith also has on-premises and cloud-hosted solutions with great pricing plans.

Flagsmith also offers a more robust feature called Remote Configuration, where you can send the values over the feature and retrieve them in your app. You can learn more about Remote Config in this post.

Do let us know if you’ve any suggestions/feedback!