I am currently working with the Foursquare API to build a simple app which will display local restaurants based on the number of checkins in has (so think Yelp sorted by Foursquare checkins vs user reviews). The Foursquare API uses authorization with a Client ID and a Client Secret token, which I wanted to store as a global variable.
Here is how to do it:
Add A Build Setting
In your app target, select Build Setting option at the top. In the bottom right corner, there is a button with a big plus called “Add Build Setting”. Click on that button, and select “Add User-Defined Setting”.
Add The Global Variable
You should now have a field where you can enter your global variable name (e.g. FOURSQUARE_CLIENT_ID) and the value (e.g. “12344455656ifsadjkfdsfjklfdjkfjk”). Pro-tip: use tabs to tab between the variable name and value!
You’d think you’re done, but you’re not!
Find The Preprocessor Macros
In the Build Settings search box, enter the word “macro”, and the Preprocessor Macros section should come up:
Set The Variables
Now, the the Debug and Release sections, define your variables (DEBUG=1) is already set for you as an example. This serves as a search and replace, so the macro will look for the word “DEBUG” in your codebase, and replace it with a 1 before compiling. For strings, you want the variable replaced with an @ sign and double quotes, so set all your string variables as follows: FOURSQUARE_CLIENT_ID=@\”$(FOURSQUARE_CLIENT_ID)\”.
Here is an example of what your settings should look like:
The blacked out parts are the actual values that are auto-completed for you. Again, make sure to copy over your variables to the Release section as well, and change them if they’re different, or your production app won’t work!
Use The Variables!
So now, every time I need to use the Foursquare Client Id or the Foursquare Client Secret token, I can just use FOURSQUARE_CLIENT_ID / FOURSQUARE_CLIENT_SECRET throughout my app, without having to remember what the actual client id or client secret is. And if my client id changes, I can easily just update the value in one place – my user defined build settings!