Storing API Keys and Other Constants in Swift 3
After your app is on the App Store, you’ll have at least two states of your app to maintain: the app as it is on the App Store, and the app that you actively add features to in development.
If you have a server running in the backend, you’ll definitely have a server for production and a server for active development. On the iOS development side, we need some way of organizing our code base to prevent crashing the production version of the app.
Constants file or the
info.plist file is commonly used to store variables which not only contain sensitive data, but might also change depending on the state of your app—like server URLs and API keys.
This is a guide to setting up different configurations of your app through schemes for different states of the app:
Release — and specifying our configurations in the
How To Add .xcconfig Files To Your XCode Project
- Create a new folder in your XCode project — I called mine
Config. I’m adding three
2. Add your configuration files to your project settings. You’ll most likely have to create an extra Configuration for
If you’re not using Cocoapods, you can skip to #3. If you are using Cocopods, you’ll have to delete the
.xcworkspace file, the
Podfile.lock, and the
Pods/ directory. Do not delete the Podfile.
Then, go to your terminal. Make sure that you’re in the project directory and run
Now, open the newly generated
.xcworkspace file and add the
.xcconfig path for Cocoapods in your own
3. Add new schemes to your project and make sure your target is your XCode project name. Set up your scheme to correspond to your configuration.
4. Now you can set variables in your config files and access them via your
Warnings and Common Pitfalls
- Beware of putting a string as a value for a key within a
.xcconfigfile — it automatically stringifies any value.
- In these examples, I pushed my
.xcconfigfiles to my repo so you can download and run the project. In a real working environment, you should put these files in your
.gitignore— and then have a private repository to keep up with updates in the config files.
Did you gain value by reading this article? Click here to share it on Twitter! If you’d like to see content like this more often, follow me on Medium and subscribe to my once-a-month newsletter below. Feel free to buy me a coffee too.