Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference an environment variable inside Obj-C code

From http://rosettacode.org/wiki/Environment_variables#Objective-C:

[[NSProcessInfo processInfo] environment] returns an NSDictionary of the current environment.

For example:

[[[NSProcessInfo processInfo] environment] objectForKey:@"MY_SRC_DIR"]

Just expose the desired var into the Environment Variables list of your current Xcode's deployment Scheme and you'll be able to retrieve it at runtime like this:

NSString *buildConfiguration = [[NSProcessInfo processInfo] environment][@"BUILD_CONFIGURATION"];

It also applies to swift based projects.

Adding Xcode Build Setting Var to Environment var

Hope it helps!! :]


Here is another way to do it:

.xcconfig file:

FIRST_PRESIDENT = '@"Washington, George"'
GCC_PREPROCESSOR_DEFINITIONS = MACRO_FIRST_PRESIDENT=$(FIRST_PRESIDENT)

objective C code:

#ifdef FIRST_PRESIDENT
    NSLog(@"FIRST_PRESIDENT is defined");
#else
    NSLog(@"FIRST_PRESIDENT is NOT defined");
#endif
#ifdef MACRO_FIRST_PRESIDENT
    NSLog(@"MACRO_FIRST_PRESIDENT is %@", MACRO_FIRST_PRESIDENT);
#else
    NSLog(@"MACRO_FIRST_PRESIDENT is undefined, sorry!");
#endif

Console output -- I've stripped out the garbage from NSLog:

FIRST_PRESIDENT is NOT defined
MACRO_FIRST_PRESIDENT is Washington, George

The only way I've found to get a build time environment variable as a string is to put it in an dictionary element like this:

<key>Product Name</key>
<string>$PRODUCT_NAME</string>

and then retrieve it like this:

NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
NSString* productName = infoDict[@"Product Name"];
NSLog(@"Product Name: %@", productName);