4

I want to open source my iOS app but still be able to build it using a CI system like Microsoft App Center. My app uses private API keys that I want to hide from my open source repository.

Fortunately App Center offers the environment variables feature, which are intended to use at build time. Their documentation says they can be used like this in bash:

$ENVIRONMENT_VARIABLE

So, say I have an environment variable called GoogleAPIKey configured in App Center, can I retrieve it like this ProcessInfo.processInfo.environment["GoogleAPIKey"] ?? "" in my app? If yes, how do I test the app on my device if only App Center has the key (I don't want to put it in my code since that would mean it would be public (do I need to use gitignore)?

Cesare
  • 9,139
  • 16
  • 78
  • 130

2 Answers2

3

I don't think you can read environment variables inside the app. You can access environment variables in a custom bash scripts only. However I think you can modify app project files inside the build script. So you may try something like this:

  1. Add a special text file to xcode project and commit it to your repository.
  2. Add environment variable with GoogleAPIKey value
  3. Write GoogleAPIKey value to the text file inside the build script.
  4. Read GoogleAPIKey value from text file with your Swift code
NShiny
  • 1,046
  • 1
  • 10
  • 19
  • I have been struggling with this same issue. Can you show how your script looks like ? I am writing to a new plist, but Its not working from device. Only locally from simulator. Not sure if I am setting wrong path or it runs in a wrong order. – ako89 Jul 10 '20 at 12:24
  • ako89, I haven't used AppCenter for quite long time and I don't have a script. However, the script should be quite straightforward. In case of text file you need to fill it with API key. Something like `echo $API_KEY_VALUE > mytextfile` should be enough. In case of plist file it is a little more tricky because you don't want to rewrite the whole content of the file. However you may fill plist with placeholder value and substitute placeholder value in plist with real key. I think `sed` command may do the trick: `sed s/PLACEHOLDER_VALUE/$API_KEY_VALUE/g -i -- path-to-plist-file` – NShiny Jul 10 '20 at 16:10
0

Edit current Scheme (Product -> Scheme -> Edit Scheme)

Add environment variables here: enter image description here

Sam
  • 145
  • 5