Use dynamic user variable with XCODEBUILD

Sometimes we need to do something unusual. For example, configure Xcode project so that it could take command line arguments and use them. Sounds simple enough? Let’s see how it works…(the sample project is here)
To be able to use user defined variable, we need to add it to the project. There are some steps to be completed:
1) Define our variable as preprocessor macros, so it is handled when the build operation is performed:
Select target -> Build settings -> Preprocessing -> Preprocessor Macros and add our variable called LABEL_TEXT for debug and release configurations:

Add User Defined Variable
Add User Defined Variable

2) Now we add user-defined setting and give this User-Defined variable the name LABEL_TEXT and a default value – a string “Jupiter” (as the largest planet in Solar system):

Add User Defined Setting
Add User Defined Setting

3) To be able to access this variable from our app, we need a reference to it. We add a keyLABEL_TEXT to Info.plist and set it to value of our user variable: $(LABEL_TEXT)
Now we can access LABEL_TEXT variable by searching for it’s value in Info.plist. If we build and run sample project using Xcode SDK, we’ll see the label with the name of the largest planed in the Solar system.

Now we jump to the main part – passing a user-defined variable from command line tools. In terminal navigate to project folder (the one, which contains .xcodeproj file). Run the following line:

xcodebuild -sdk iphonesimulator8.4 LABEL_TEXT="Mercury" clean build

it tells Xcode command line tool that we need to build for simulator architecture and clean before the build. Also it passes a new argument to our variable LABEL_TEXT. When the build process is completed, we will see the folder named “build” in our project folder, which, in turn, contains the folder Release-iphonesimucator. Navigate to it, make sure your simulator is open, then run:

xcrun simctl install booted YourAppName.app

(in case of sample project, that will be xcrun simctl install booted UserDefinedLabel.app)
This will install the app into your simulator.
Now we can go to the simulator, press app icon and observe the effect of user-defined variable. Instead of showing the name of the largest planed in Solar system, the label now shows the name of the smallest planet!

Simple as that, we build the app we can run in simulator using the command-line arguments!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s