为了能够测试 GameKit 功能,我希望能够检测代码是否正在 Playground 中运行,以便它可以跳过网络调用。有办法做到这一点吗?
编辑:
忘掉 GameKit——那只会让问题变得更加混乱。在许多不同的场景中这都会很有用。这实际上只是一个关于特定函数调用是否存在的简单问题:如果代码在 Playground 中运行,是否有一个方法返回
true
?
我不知道有记录的方法可以做到这一点,但是您可以做一些未记录的事情。
以下技术适用于 Xcode 7 with Swift 2.2 和 Xcode 8 with Swift 3.0、macOS 和 iOS 游乐场:检查标识符以
"com.apple.dt"
开头的包。
// Swift 2.2
if NSBundle.allBundles().contains({ ($0.bundleIdentifier ?? "").hasPrefix("com.apple.dt.") }) {
print("in playground")
} else {
print("not in playground")
}
// Swift 3.0
if Bundle.allBundles.contains(where: { ($0.bundleIdentifier ?? "").hasPrefix("com.apple.dt.") }) {
print("in playground")
} else {
print("not in playground")
}
请注意,
com.apple.dt.
不是专门为游乐场相关捆绑包保留的前缀; dt
是“开发者工具”之类的部分标准。因此,在某些情况下,您可能会得到误报:有一个匹配的捆绑包,但您不在游乐场中。我不知道有任何这样的情况,但可能有一些。我确实在 Xcode 7 下的 macOS xib 中测试了 IBDesignable
视图,并且它没有加载任何 com.apple.dt.
包。
我使用包含“swift-playgrounds”的应用程序包 ID 更新了之前的答案:
public var inPlayground: Bool {
if Bundle.allBundles.contains(where: { ($0.bundleIdentifier ?? "").contains("swift-playgrounds") }) {
return true
} else {
return false
}
}