Determinate the build configuration at runtime in Swift using macro
Today when developing iOS apps is common to have to work with multiple environments inside the same project (staging and production for example). I am going to show you how to change environment based on build configuration, like this you will never release an app in production pointing out development endpoints.
Let’s say that you have 3 build configurations (Debug, Release and AdHoc):
Now we need to add flags to the AdHoc and Debug versions, look for Other Swift Flags in the Build Settings tab and add :
- “-DADHOC” for Adhoc build configuration
- “-DDEBUG” for Debug build configuration
There are no need to call the flag DEBUG or ADHOC but you need to add -D at the start of the word you going to use.
I made a small struct to check the flag at runtime using macro.
Then to check if you are in production :
let production = Env.isProduction()
That’s it!
You may asked how can I test my app in production. No there are no need to run the app on release.
We going to add a new Environment Variable to our Scheme, let’s call it forceProduction:
Now just update our struct:
Now if you want to test in production just click on the check box.