How to hide your API keys

If you’d like to have all your code open sourced by default and available on GitHub, then how do you hide your API keys and other sensitive data?

This is the flow that I usually follow. If you have any other suggestions, please leave them in comments. 🙏🏽

  1. In your iOS project, create a file to store your API keys. For example: Constants
  2. Add any sensitive data to this file like your API keys, OAuth secret, etc.
  3. Throughout your codebase, refer to your API keys as variables declared in your Constants file. For example:
let apiKey = MyOpenWeatherApiKey
// instead of 
// let apiKey = "12345678910"

4. In the terminal create a .gitignore file and open it in your text editor of choice (atom, sublime, textedit, etc.). I prefer Xcode.

touch .gitignore
open .gitignore -a Xcode

5. In the .gitignore file, enter any file names that you do NOT want git to track/commit/push. In this case you would enter:

Constants.swift

6. Save and close it.

7. Type git status. You should see the .gitignore file ready to be tracked. You should NOT see the Constants.swift file.

git status 

8. Type git add ., and git status again. Make sure the Constants.swift file did not get added. If everything looks good, you’re ready to commit and push.

git add . 
git status 

9. Add a note to your project’s README.md on GitHub explaining users how to recreate the file, and/or insert their own API keys, to be able to run the project.

For example, in your codebase it could look like this:

let apiKey = "INSERT YOUR API KEY HERE"

Resources:

https://gist.github.com/derzorngottes/3b57edc1f996dddcab25

https://medium.com/life-at-artsy/why-your-default-setting-should-be-open-source-f7cd2ed572b7#.anl6514a8