SpacePod 17 - App Secrets
Thoughts
Lot’s of ways to do this, and all of them have drawbacks. We are doing it this way to keep things simple. Warning, this approach is simple, but the api key will in plaintext in the app bundle!!!
Other Methods
- Environment setting
- CI/CD
- Shared iCloud database
- Bypass the API altogether
Objectives
- Use your api key instead of the demo key
- Make sure we don’t check our api key into the repo
Steps
- Update Network.swift
- Create .gitignore
- Copy & paste from github
- Add Secrets.json to .gitignore?
- Add Secrets.json to project and target
- Create Secrets.swift model
- Load apiKey from Secrets.txt ?? DEMO_KEY
Secret.swift
- New Group “Models”
- New Type Secret
import Foundation
struct Secret: Codable {
let apiKey: String
}
Decoding
var toSecret: Secret? {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try? decoder.decode(Secret.self, from: self)
}
Update Network
Delete getString()
& getPod()
import Foundation
class Network {
let baseUrl = "https://api.nasa.gov/planetary/apod"
let apiKey = "?api_key=" + (File.data(from: "Secrets", withExtension: .json)?.toSecret?.apiKey.description ?? "DEMO_KEY")
func getPods() async -> [Pod]? {
let url = URL(string: "\(baseUrl)\(apiKey)&count=20")!
do {
let request = URLRequest(url: url)
#if DEBUG
print("🌎 request: " + request.debugDescription)
#endif
let (data, response) = try await URLSession.shared.data(for: request)
#if DEBUG
print("🌎 response: " + response.debugDescription)
#endif
return data.toPods
}
catch {
#if DEBUG
print("🌎 error: " + error.localizedDescription)
#endif
return nil
}
}
}
Create .gitignore
- Add a new empty file at the root of the project and name it “.gitignore”. Be sure to notinclude it in our target.
- Copy and paste the contents of Swift.gitignore into .gitignore.
- Add Secrets.json to .gitignore
# Project
Secrets.json
Add Secrets.json
- Select the project
- Right click to create a new file named Secrets.json
- Be sure to include it with SpacePod target
- Add the following json
- Be sure to change apiKey to your api key from https://api.nasa.gov and save
{
"api_key" : "PASTE_YOUR_API_KEY_HERE"
}