【问题标题】:How can I get an environment variable from Xcode in my app如何在我的应用程序中从 Xcode 获取环境变量
【发布时间】:2015-01-31 21:50:15
【问题描述】:

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

如果我在操场上测试它

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

env 将是“YES”。

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

因为只有在安装了插件后我才会打印出带有特定 esc 序列的彩色文本,所以我想获取有关 Xcode env var 的信息。

我该怎么做?

【问题讨论】:

  • 我遇到了同样的问题。您找到解决方案了吗?

标签: ios xcode swift


【解决方案1】:

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

请注意,如果您在没有 XCode 的情况下运行应用程序,则不会设置环境变量。

【讨论】:

  • 谢谢,这个方法我也用过。但是,如果我将我的源代码分享给其他开发人员,我必须解释要做什么,是否安装了 XcodeColors。我想从我的应用中自动完成。
  • 注意Xcode不是BASH运行的,所以这里定义的环境,只存在于Xcode中。
  • 另请参阅 NSHipster 关于可用环境设置的有用博客:nshipster.com/launch-arguments-and-environment-variables
【解决方案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
    }
}

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2019-09-22
    • 2021-07-15
    • 1970-01-01
    相关资源
    最近更新 更多