DEV Community

Cover image for How to Easily Use Feature Flags in Swift with Firebase
Silvia España Gil
Silvia España Gil

Posted on

How to Easily Use Feature Flags in Swift with Firebase

Hola mundo!

I always like to start my posts by explaining why I’m writing an article, but feel free to skip this part if you’re in a hurry🏃🏽‍♀️.

Back at my first job, there were these refinement sessions where they’d say, "Should we protect this with a Feature Flag?" At that time, I had no idea what a Feature Flag was. When I finally asked a team member and learned about it, my mind was blown🤯. It felt like magic ​🔮 – a way to safely roll out changes without fear of breaking the app. If something went wrong, you could just flip the Feature Flag. Simple as that!

In that project, we used LaunchDarkly for managing Feature Flags. However, I recently discovered that Firebase has a feature for setting Feature Flags too, and the setup is ✨ SO EASY and user-friendly ✨ that I immediately fell in love with it. I couldn’t wait to share this with you!

Today, I’m excited to show you how to implement Feature Flags in an iOS app using SwiftUI and Firebase Remote Config.

If you’ve never used Feature Flags before, you’re in for a treat. This powerful tool lets you control your app’s features in real-time, without pushing updates to the App Store 🙌!

So, let's get to it 💪!


What’s a Feature Flag?​.

Before getting into the code, let’s quickly cover what a Feature Flag is. Imagine you’re working on an awesome new feature for your app, but you’re unsure whether to roll it out to all users or just a select few.

Or perhaps the feature is quite big, and you want to start with the UI first, then add the business logic in stages.

Feature Flags are your best friends here! They’re like switches you can toggle to turn functionalities on or off in real-time. No need to create new app versions and submit them to the Store.

They’re fantastic for A/B testing, gradual rollouts, or controlling features during special events. Sounds amazing, right?

Let’s get it set up!💻​

📢​For the complete code used in this tutorial, be sure to check out my GitHub repository📢


👉🏽​ Step 1: Set Up Firebase in your iOS Project​.


First, you need to add Firebase to your project. Here’s how:

1) Add Firebase to Your Xcode Project:

  • Open your project in Xcode.
  • Go to "File" > "Add Packages..." and enter the Firebase repository URL: https://github.com/firebase/firebase-ios-sdk.
  • Choose the Firebase Remote Config package and add it to your project.

2) Configure Firebase in Your App:

  • Go to the Firebase Console and create a new project.
  • Follow the instructions to add an iOS app to your Firebase project (the guide is pretty straightforward).
  • Download the GoogleService-Info.plist file provided and add it to your Xcode project.

👉🏽​Step 2: Initialise Firebase​.

Now that Firebase is set up we have to initialise it and use it. Let’s create a simple Proof of Concept (PoC) to see the power of Feature Flags in action.

1) Initialise Firebase in your app

Add this code to your AppDelegate. You can check the official Firebase documentation if you need more details.

class AppDelegate: NSObject, UIApplicationDelegate {

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

    FirebaseApp.configure()

    return true
  }
}
Enter fullscreen mode Exit fullscreen mode

Now in your app entry point, use UIApplicationDelegateAdaptor to link your AppDelegate

@main
struct FirebaseFeatureFlagsApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

👉🏽​Step 3: Configure Remote Config in Firebase

Now, let’s set up the Feature Flags in the Firebase Remote Config Console:

1) Add parameters in Firebase Console:

  • Go to your Firebase Console and select the Remote Config option.
  • Once in Remote Config, select the button Add parameter
    • Choose the parameter name and the data type for the param
    • Optional you can add a description, this is always a good idea
    • Now set the default value that you want.
    • Publish the changes

Shows how the add parameter view looks in the firebase console


👉🏽​Step 4: Create a view that will use the Feature Flag

To visualize it, let’s create a simple view where the background colour changes based on the Feature Flag. As you may see in the code there's a boolean value isBlueBackgroundEnabled that changes certain things including the background and the text colour.

This value is my Feature Flag.


struct ContentView: View {
    @State private var isBlueBackgroundEnabled = false

    var body: some View {
        ZStack {
            (isBlueBackgroundEnabled ? Color.blue.opacity(0.5) : Color.pink.opacity(0.5))
                .edgesIgnoringSafeArea(.all)

            HStack {
                Text("Hello, Feature Flags!")
                    .font(.title)
                    .foregroundColor(isBlueBackgroundEnabled ? .white : .black)

                Image(systemName: "heart")
                    .imageScale(.large)
                    .foregroundColor(isBlueBackgroundEnabled ? .white : .black)
                    .onTapGesture {
                        fetchRemoteConfig()
                    }
            }
        }
        .onAppear {
            fetchRemoteConfig()
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

👉🏽​Step 5: Fetch the Feature Flag value from Firebase

🔎​​​Please note the .onAppear method in the previous example 🔎​

As you see in our view I've called fetchRemoteConfig() this method retrieves the current Feature Flag configuration from Firebase.

Here’s how it works:

extension ContentView {
    private func configureRemoteConfig(_ remoteConfig: RemoteConfig) {
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0 
        remoteConfig.configSettings = settings
        remoteConfig.setDefaults([
            "isBlueBackgroundEnabled": NSNumber(value: false),
            "isNewFeatureEnabled": NSNumber(value: false)
        ])
    }

    private func fetchRemoteConfig() {
        let remoteConfig = RemoteConfig.remoteConfig()
        configureRemoteConfig(remoteConfig)

        remoteConfig.fetch { status, error in
            if status == .success {
                remoteConfig.activate { _, _ in
                    // Access your Feature Flags here
                    self.isBlueBackgroundEnabled = remoteConfig["isBlueBackgroundEnabled"].boolValue
                    // Add all your Feature Flags
                }
            } else {
                print("Error fetching remote config: \(String(describing: error))")
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

🤔Curious about how these methods work? Let me break it down a bit for you🤔

1) configureRemoteConfig(_:): This method sets up the Remote Config instance with settings. The minimumFetchInterval of 0 is for development purposes, meaning you can fetch data from Firebase without waiting.
setDefaults sets a default value for the Feature Flag, which is used if there’s no configuration fetched.

2) fetchRemoteConfig(): This method is where the magic happens. It starts by fetching the latest configuration from Firebase. If the fetch is successful, it activates the new configuration and updates the Feature Flag state based on the fetched value. If something goes wrong, it prints an error message.

📢​For the complete code used in this tutorial, be sure to check out my GitHub repository📢


🎉​Check what you did

Now for the fun part. 🏗️​Build your code.

If you set your Feature Flag to false, you should see a lovely pink background. Change the value to true in the Remote Config Console, and voila 🪄 your background colour will change!

Gif of the view changing colour depending on the value of the feature flag


And there you have it! Implementing Feature Flags with Firebase Remote Config is straightforward and incredibly powerful🔥. You can toggle features in real-time without needing to update the app, which makes your development process more flexible and efficient.

I hope this guide helps you make your apps more dynamic and lets you experiment with new features with confidence🚀.


If you enjoyed this, please share, like, and comment. I hope this can be useful to someone and that it will inspire more people to learn and code with Swift 💻✨

Top comments (0)