Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an environment variable from Xcode in my app

Tags:

xcode

ios

swift

I have installed the Xcode plugin for XcodeColors from robbie hanson. (see https://github.com/robbiehanson/XcodeColors)

If I test it in a playground

let dict = NSProcessInfo.processInfo().environment
let env = dict["XcodeColors"] as? String

env would be "YES".

But, if I use the same code in my app, env would be nil, because the app is running on their own process.

Because I would print out colored text with specific esc sequences only if the plugin is installed, I want get the information about the Xcode env var.

How can I do that?

like image 482
MUECKE446 Avatar asked Dec 03 '14 10:12

MUECKE446


2 Answers

Edit your scheme -> Select the "Run" section -> Select "Arguments" tab -> Add the environment variable.

Be careful, environment variables are not set if you run the app without XCode.

like image 135
Imotep Avatar answered Nov 13 '22 09:11

Imotep


I ran into the same problem with XcodeColors. I ended up solving it with a simple script build phase. It checks to see if XcodeColors is installed or not and sets/adds a key to the Info.plist in the build. So create a new "Run Script Build Phase" and put this in there:

xcodeColorsDir="$USER_LIBRARY_DIR/Application Support/Developer/Shared/Xcode/Plugins/XcodeColors.xcplugin/"
xcodeColorsInstalled=0
if [ -d "$xcodeColorsDir" ]; then
    # Directory exists, therefore, XcodeColors is installed
    xcodeColorsInstalled=1
fi

infoPlistPath="${TARGET_BUILD_DIR}/${INFOPLIST_PATH}"
existingValue=$(/usr/libexec/PlistBuddy -c "Print :XcodeColorsInstalled" "$infoPlistPath")
if [ -z "$existingValue" ]; then
    # Key already exists so overwrite it
    /usr/libexec/PlistBuddy -c "Add :XcodeColorsInstalled bool $xcodeColorsInstalled" "$infoPlistPath"
else
    # Key doesn't exist yet
    /usr/libexec/PlistBuddy -c "Set :XcodeColorsInstalled $xcodeColorsInstalled" "$infoPlistPath"
fi

Then, you can access the Info.plist param during runtime with something like:

func isColorizedLoggingEnabled() -> Bool {
    if let colorizedLoggingEnabled = NSBundle.mainBundle().infoDictionary?["XcodeColorsInstalled"] as? Bool {
        return colorizedLoggingEnabled
    } else {
        return false
    }
}
like image 27
Brian Avatar answered Nov 13 '22 09:11

Brian