Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode: how to compile environment variables and refer to them in Swift?

I have an API key defined on my CI/CD platform like so:

export API_KEY="XXXXXXXXXX"

Is there a way I can somehow compile this variable with my build so that I can reference it in Swift and not have to worry about the variable being defined in the binary's environment at runtime? I can't use ProcessInfo.processInfo.environment obviously, because the API key is only defined in my CI/CD environment. I want to have my binary compiled with the key so that when I distribute my app the key is available to use.

My use case is that I want to avoid putting an API key in my git repository, and instead fetch it from the CI/CD platform when the build is generated. If there is a way to inject an environment variable that then gets compiled as part of the binary, that would be ideal.

like image 343
sschilli Avatar asked Oct 15 '22 09:10

sschilli


1 Answers

You can do a pre-action script in Xcode build section Xcode pre-action build

Which will modify placeholder with the following code:

let apiKey : String = "<# THE_API_KEY #>"

Modify the code directly in the source file

Before each build.

And you can add another one if you have a production key in the Archive pre-action

Exemple

place the apiKey variable in the file you want to access it

In Pre-action do a script to remplace a place holder text like THE_API_KEY

The script will look like this

 cat $PROJECT/$PATH_TO_FILE | sed 's/THE_API_KEY/YOUR_KEY' > $PROJECT/$PATH_TO_FILE

Don't forget to clean the code to avoid put the API key in you commit

With a Post-action

cat $PROJECT/$PATH_TO_FILE | sed 's/YOUR_KEY/THE_API_KEY' > $PROJECT/$PATH_TO_FILE
like image 162
Sombre Osmo'z Avatar answered Oct 21 '22 05:10

Sombre Osmo'z