Calling an environment variable from a .xcconfig file in swift

I'm trying to setup a GitHub repository for a project that will involve the use of an API Key. In order to keep that key a secret, I have decided to make a .xcconfig file with the API Key and add the .xcconfig file to my .gitignore. So far I have linked the file with my build settings for the app target. But I'm not actually sure how to go about calling the variable in my swift code. I know that there are environment variables within the Xcode build schemes, but I'm not sure how you would call them from there either. Is there some kind of framework that I need to call? Nothing online seems to be pointing to linking to the actual file itself.

Accepted Reply

You need first to add a variable inside your Info.plist, than you can read the variable from it.

For example if you have a MyConfig.xcconfig file like this:

MY_SECRET_API_KEY = mysupersecretapikeyvaluehere

In your Info.plist you should add an entry like this:

<key>MySecretApiKey</key>
<string>$(MY_SECRET_API_KEY)</string>

Finally in your code read the value of your variable like this:

guard let infoDictionary: [String: Any] = Bundle.main.infoDictionary else { return }
guard let mySecretApiKey: String = infoDictionary["MySecretApiKey"] as? String else { return }
print("Here's your api key value -> \(mySecretApiKey)")
  • That worked, thank you!

  • What about if your key is multiline like ---- BEGIN PRIV KEY ---- isaf9082308fh089h0h3f afw098h9h320hf90h930f 3290f90hfsdfadf3223323 ---- END PRIV KEY ----

    How would you add this to config?

Add a Comment

Replies

You need first to add a variable inside your Info.plist, than you can read the variable from it.

For example if you have a MyConfig.xcconfig file like this:

MY_SECRET_API_KEY = mysupersecretapikeyvaluehere

In your Info.plist you should add an entry like this:

<key>MySecretApiKey</key>
<string>$(MY_SECRET_API_KEY)</string>

Finally in your code read the value of your variable like this:

guard let infoDictionary: [String: Any] = Bundle.main.infoDictionary else { return }
guard let mySecretApiKey: String = infoDictionary["MySecretApiKey"] as? String else { return }
print("Here's your api key value -> \(mySecretApiKey)")
  • That worked, thank you!

  • What about if your key is multiline like ---- BEGIN PRIV KEY ---- isaf9082308fh089h0h3f afw098h9h320hf90h930f 3290f90hfsdfadf3223323 ---- END PRIV KEY ----

    How would you add this to config?

Add a Comment

This warrants the remark that now anyone who has the App can see your mysupersecretapikeyvaluehere, and it is now public

As @below pointed out, this is not a secure practice. Sensitive data should NEVER be store on the client side. If you product involves secrets like this to function you should consider implementing the functionality on the server side.