How to use Feature Flags in an iOS App [with code examples]
Tags: ios, webdev, programming, tutorial
Published: 2022-02-02 12:24:58

If you ask yourself: 

**How to test & deploy new features in your app without sending ap App Store update?**

or

**How to release your new version to only 1% (or 5%, or 50%) of the userbase?** 

You definitely need to read this article. Today we'll talk about Feature Flagging for IOS apps. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ujcfjbc86ds07u94yfof.jpeg)

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.

## Why you should use Feature Flags (aka feature toggles) for IOS app

Here is the list of main benefits:

**1. Deploy features without risk**

Even if something goes wrong, you can always rollback update easily. 

**2. Maintain release cycle easier**

Even if some part of your code are unfinished, you still can release it and once everything ready just switch toggle and new feature will be in your app without sending an App Store update. 

**3. A/B/n test & Canary deployment**

With just feature flagging, you can release your new features & updates to only a group of people. It might be your beta testers who can use new updates in production or you can simply A/B/n test everything and check the impact on your metrics. 

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

1. Creating Feature Flag on Flagsmith ([Sign up for free and use feature flags](https://app.flagsmith.com/signup?utm_source=devto&utm_medium=iosapp))
2. Installing the Flagsmith iOS SDK
3. Working with the Flagsmith iOS SDK
4. Testing the Feature Flag
5. Testing Different Environments
6. So let’s get started!


## Getting Started with iOS Feature Flag

Flagsmith has a sample project to showcase a demo feature flag, and [you can download the starter project from here](https://github.com/Flagsmith/sample-ios-app). 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:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zqlienn8hcaxi8uqi5g.png)

You can sign up via GitHub, Google or email:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ylisv2xfux324shxo1ww.png)

Then, create an organization to house all your projects:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4unbrwzgb2xsozxjsa9.png)

After creating the organization, create the project that will contain the iOS feature flag. 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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ku0blsla3zkruv7conil.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9cgmzbwa578buxr6si5.png)

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

## Creating a Feature Flag on Flagsmith 

[>>Sing up for free and use feature flags!](https://app.flagsmith.com/signup?utm_source=devto&utm_medium=iosapp)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtgceqf4l7hg5a38bal7.png)

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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8q1ei4zru50qpsfma96y.png)

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, .xml, toml 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:

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

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:


```
import FlagsmithClient
extension FlagsmithExampleApp {
  private func initializeFlagsmith() {
    Flagsmith.shared.apiKey = "<#YOUR API KEY#>"
  }
}

```

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

```
@main
struct FlagsmithExampleApp: App {
  init() {
    initializeFlagsmith()
  }
  var body: some Scene {
    WindowGroup {
      MainView()
    }
  }
}
```

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:

```
Flagsmith.shared.getFeatureFlags() { (result) in
    switch result {
    case .success(let flags):
        for flag in flags {
            let name = flag.feature.name
            let value = flag.value?.stringValue
            let enabled = flag.enabled
            print(name, "= enabled:", enabled, "value:", value ?? "nil")
        }
    case .failure(let error):
        print(error)
    }
}
```

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

```
enum FeatureFlags: String {
  case showOnboarding = "show_onboarding"
  var id: String {
    self.rawValue
  }
}
```

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:

```
private func initializeFlagsmith() {
  Flagsmith.shared.apiKey = "<#YOUR API KEY#>"
  Flagsmith.shared.getFeatureFlags { (result) in
    switch result {
      case .success(let flags):
        for flag in flags {
          // Comparing the feature flag's name to the particular ID.
          if flag.feature.name == FeatureFlags.showOnboarding.id {
            DispatchQueue.main.async {
              viewModel.showOnboarding = flag.enabled
            }
          }
        }
      case .failure(let error):
        print(error)
    }
  }
}
```

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

```
Flagsmith.shared
  .hasFeatureFlag(withID: FeatureFlags.showOnboarding.id, forIdentity: nil) { (result) in
  switch result {
    case .success(let value):
      DispatchQueue.main.async {
        viewModel.showOnboarding = value
     }
    case .failure(let error):
      print(error)
  }
}
```

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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2f24r75d4u9lh40k6ms9.png)
 

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 iOS Feature Flag
Go to the Flagsmith project and toggle the feature flag show_onboarding by switching the **OFF ** button to **ON**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5qny4m054sc6gu2douky.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekiqf7p13d50dy82qsla.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzl49yqsjtwlkdn0pz0c.png)


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8sqdv9giqmbfcnlrvmix.png)

## Testing Different Environments
[>>Sign up for free and use feature flags!](https://app.flagsmith.com/signup?utm_source=devto&utm_medium=iosapp)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18a3srpmri2kuqivmujl.png)

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:

```
#if DEBUG
    Flagsmith.shared.apiKey = "<#YOUR DEVELOPMENT API KEY#>"
 #else
    Flagsmith.shared.apiKey = "<#YOUR PRODUCTION API KEY#>"
 #endif 
```

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fxx099dku94c5uz7lth3.png)

From the sidebar, select **Run**. Under the **Info** tab, change the build configuration to **Release**: 
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tw3g8pvu1qfk8squbob3.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vgnyxr8c6fn465zq96ly.png)

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](https://github.com/Flagsmith/sample-ios-app). 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](https://flagsmith.com/open-source/) for your next Xcode project. Flagsmith also has [on-premises](https://flagsmith.com/on-premises-and-private-cloud-hosting/) and [cloud-hosted](https://flagsmith.com/cloud/) solutions with great pricing plans.

[>>Sign up for free and use feature flags!](https://app.flagsmith.com/signup?utm_source=devto&utm_medium=iosapp)

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!  

Btw, [the original article was posted here](https://flagsmith.com/blog/feature-flags-in-an-ios-app/).