Issue
I have 2 API keys that are currently used in my code, and are also hardcoded inside the code. These keys need to be removed from the code completely and added in as environment variables instead from outside Xcode during the build phase. So far I have tried having this script
export API_KEY=keyvalue
as a Run Script that occurs before Compile Sources in the build phase, having that script as a Pre Action in the project's scheme, and also building the app from the command line with this but the environment variables for the given keys are always null.
xcodebuild -project MyProject.xcodeproj \
-scheme "My Scheme" \
-sdk iphoneos \
-destination 'platform=iOS,name=<devicename>' \
-derivedDataPath './output' \
API_KEY='KEY' \
SECOND_API_KEY='KEY' \
When manually building the project like this I can see the keys being exported correctly like all the other settings but cannot seem to access them with NSProcessInfo.processInfo.environment objectForKey:@"API_KEY"
or with NSUserDefaults. I have also tried editing the scheme in Xcode so that the environment variables are set as API_KEY = $(API_KEY) along with the above but that did not work, as well as setting default values for these keys in Build Settings which also did not work. Is this actually possible to do? Thanks.
Solution
If I'm understanding you correctly you are misunderstanding environment variables, if I'm not my apologies.
You cannot access environment variables that were set during the build process when your application runs – unless that build process writes the values into the code or some configuration file.
Environment variables are passed to a process when it is started, your code can access those variables. While the names of the environment variables will need to be embedded in your code the values of those variables is not.
It sounds like you wish to distribute a compiled app without the API keys it needs to run and then supply those when it is run. You could do this by using a small shell script to set environment variables and then launch your app. Or you could use a scheme like those used for serial numbers, so your users have to enter the API keys (just tell them they are serial numbers ;-)) when your app is first launched and then store those in a suitable file (e.g. in your app's preferences or application support folder) obfuscated in whatever way you choose. HTH
Answered By - CRD Answer Checked By - Dawn Plyler (WPSolving Volunteer)