如何从Xcode中获取应用程序的环境变量

10

我已经从robbie hanson处安装了XcodeColors的Xcode插件。(请参见https://github.com/robbiehanson/XcodeColors

如果我在playground中测试它

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

env的值将会是"YES"。

但是,如果我在我的应用程序中使用相同的代码,env会是nil,因为该应用程序正在运行它们自己的进程。

由于只有插件安装了,我才会打印出带有特定转义序列的彩色文本,我想获取关于Xcode环境变量的信息。

我该如何做到这一点?


我也遇到了同样的问题。你找到解决方案了吗? - Tiago
2个回答

13

编辑您的方案 -> 选择“运行”部分 -> 选择“参数”选项卡 -> 添加环境变量。

注意,如果不使用XCode运行应用程序,则不会设置环境变量。


谢谢,我也使用了这种方法。但是,如果我将我的源代码分享给另一个开发人员,我必须解释需要安装XcodeColors还是不需要。我希望能够自动从我的应用程序中完成这个过程。 - MUECKE446
请注意,Xcode不是由BASH运行的,因此在此定义的环境仅存在于Xcode中。 - Efren
请参阅来自 NSHipster 的有关可用环境设置的有用博客:http://nshipster.com/launch-arguments-and-environment-variables/ - Efren

2

我也遇到了XcodeColors的同样问题。最终我通过一个简单的脚本构建阶段解决了这个问题。它会检查XcodeColors是否已安装,并在构建中设置/添加一个键到Info.plist。因此,请创建一个新的“运行脚本构建阶段”,并将以下内容放入其中:

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

接下来,您可以使用以下方式在运行时访问 Info.plist 参数:

func isColorizedLoggingEnabled() -> Bool {
    if let colorizedLoggingEnabled = NSBundle.mainBundle().infoDictionary?["XcodeColorsInstalled"] as? Bool {
        return colorizedLoggingEnabled
    } else {
        return false
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接