In the iOS Foundations Module 6, Lesson 4, we use the Yelp API key.
- What’s the best way to keep this API key secret in GitHub?
- In the App Store, do the Apple reviewers need access to your API key?
- Can you securely compile the app with the API key, or might someone decompile it to get your secret?
My current solution, so I can publish to my repo is to use something similar to a .env
file. However, when I went to create the .env
, it warned me that the project wouldn’t be able to read from it. So instead, I created a ProdEnv.swift
with a client
and apiKey
property. Then, I added another file ProdEnvExample.swift
that has a comment representing the struct that I reference later with my credentials. Last step was to add the ProdEnv.swift
file to the .gitignore
, so it does not get committed.
FYI:
- Chris also explains a similar way with the
.gitignore
, or removing the API key prior to committing here: CodeWithChris - this video explains how to create a .gitignore file at the 6:00 mark: CodeWithChris
ProdEnvExample.swift
/*
This serves as an example struct struct, so we do not commit our API key within our Git repo.
Copy the below into a new ProdEnv.swift file, then insert your credentials as shown below
import Foundation
struct YelpAPICreds {
let client = "<insertClientStringHere"
let apiKey = "insertApiKeyHere"
}
*/
Then, in my ContentModel
, I create an object of this struct, and use the API key in the request header:
// See ProdEnvExample on how to insert your API credentials
let apiCreds = YelpAPICreds()
// Add Authorization headers with our API key
request.addValue("Bearer \(apiCreds.apiKey)", forHTTPHeaderField: "Authorization")
However, I’m curious if there is a better practice, and also how Apple reviews this.