向 info.plist 添加了自定义键,当我从 Swift 中的 Playground 访问时,它是 nil

Ult*_*rus 3 plist swift xcode7

使用 Xcode 7.2(在 Yosemite 上),我似乎无法从游乐场访问 info.plist 中的自定义密钥:

import UIKit
var str = "Hello, playground"
let app_id = NSBundle.mainBundle().infoDictionary?["MyAppID"] as? String
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,app_id 为 nil。我期望它是字符串“TEST”

我将它包含在我的 info.plist 中,如下所示:

在此输入图像描述

游乐场是否有一些我没有读过的限制?

如果我打印所有密钥,则我的自定义密钥丢失:

let dict = NSBundle.mainBundle().infoDictionary!
for k in dict.keys {
  print("\(k)")
}
Run Code Online (Sandbox Code Playgroud)

打印以下内容:

DTSDKName
CFBundleIdentifier
CFBundleSupportedPlatforms
CFBundleInfoDictionaryVersion
LSRequiresIPhoneOS
CFBundleNumericVersion
DTPlatformName
CFBundleShortVersionString
CFBundleVersion
UIViewControllerBasedStatusBarAppearance
UIRequiredDeviceCapabilities
UIStatusBarHidden
CFBundlePackageType
UIDeviceFamily
CFBundleExecutable
CFBundleInfoPlistURL
LSBackgroundOnly
CFBundleName
CFBundleDevelopmentRegion
Run Code Online (Sandbox Code Playgroud)

如果我查看捆绑包名称,如下所示:

let name = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String
Run Code Online (Sandbox Code Playgroud)

我看到了游乐场的名称,而不是工作区的名称。我可以获取该项目的 info.plist 吗?

Rob*_*ier 5

游乐场没有Info.plist文件。游乐场是独立的。将它们添加到项目中不会导致它们访问项目中的文件。他们只能访问自己包中的文件。

您可以将 plist 文件作为资源添加到游乐场并以这种方式读取它(使用pathForResourceNSDictionary(contentsOfFile:),但您不能使用objectForInfoDictionaryKey它。您不能将其命名为“Info.plist”,因为这会与自动生成的冲突使用Info.plist Playgrounds来运行。

例如,如果您将 plist 复制到 Resources 文件夹中,将其命名为MyInfo.plist,然后加载它:

let infoPath = NSBundle.mainBundle().pathForResource("MyInfo.plist", ofType: nil)!
let info = NSDictionary(contentsOfFile: infoPath)!
Run Code Online (Sandbox Code Playgroud)

这与真正的 Info.plist 并不完全相同,因为类似的东西$(EXECUTABLE_NAME)不会被扩展。

但这里的要点是,playground 位于自己的包中,与应用程序无关,并且在运行时动态创建自己的 Info.plist。您在这里尝试执行的操作与游乐场当前的工作方式不符。

理解这一切的一个关键部分是游乐场是真实的应用程序。它们被编译并构建成带有自己的捆绑包的可执行文件,该捆绑包安装在构建目录中。检查一下NSBundle.mainBundle().bundlePath看看哪里。当游乐场运行时,它不知道它的源代码来自哪里,更不用说它可能位于其中的一些更大的目录结构。甚至宏也__FILE__被丢弃(它返回<EXPR>)。

我希望他们将来能够改进这一点,因为目前有很多类似的事情使得它们很难用来探索现有的代码库。它们确实是为了探索独立的 Swift 的一小部分。我经常发现自己构建小型命令行应用程序而不是游乐场。对于非 UI 工作,命令行应用程序可能更强大。