Search code examples
swiftenvironment-variablestvos

Swift environment variable returns nil when building app


Description

I have a problem with environment variables. When I build my app and it's running, everything goes fine, but when I press "stop" or I archive it for app store, the environment variable returns nil (or an empty string, I'm not quite sure yet).

How to reproduce:

  1. Build the app
  2. Run it on the simulator ("Hello world" will appear)
  3. Stop the app
  4. In the simulator, go back in the app ("Hello word" won't appear)

Minimal reproduction:

class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = ProcessInfo.processInfo.environment["testVariable"]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

The label Outlet references a simple storyboard

storyboard screenshot

And here is the config for my env variables

Variables configuration

Finally, here is a minimal reproduction of the problem on a github repo https://github.com/MasterBroki/test-environment-variable

Thanks for your answers!


Solution

  • Xcode passes environment variables from a scheme to the iOS runtime. When you run the application outside of Xcode, they are not passed. I've also run into this limitation, and you can find a similar question here.

    An alternative to this approach is to use pairings of configurations (such as Debug, Release, or one you make for a specific purpose) and "Preprocessor Flags" OR "Other Swift Flags." You can find some guidance for this approach here.