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. 🙏🏽
- In your iOS project, create a file to store your API keys. For example: Constants
- Add any sensitive data to this file like your API keys, OAuth secret, etc.
- 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.
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:
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.
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 .
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"