在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
我在Swift 3中使用了下面的代码
if TARGET_IPHONE_SIMULATOR == 1 {
//simulator
} else {
//device
}
其他回答
下面是一个基于HotJard上面的精彩答案的Xcode 11 Swift示例,这也添加了一个isDevice Bool,并使用SIMULATOR_UDID而不是name。变量赋值是在每一行上完成的,这样你就可以更容易地在调试器中检查它们。
import Foundation
// Extensions to UIDevice based on ProcessInfo.processInfo.environment keys
// to determine if the app is running on an actual device or the Simulator.
@objc extension UIDevice {
static var isSimulator: Bool {
let environment = ProcessInfo.processInfo.environment
let isSimulator = environment["SIMULATOR_UDID"] != nil
return isSimulator
}
static var isDevice: Bool {
let environment = ProcessInfo.processInfo.environment
let isDevice = environment["SIMULATOR_UDID"] == nil
return isDevice
}
}
还有DTPlatformName的字典条目,它应该包含模拟器。
在现代系统中:
#if targetEnvironment(simulator)
// sim
#else
// device
#endif
就是这么简单。
斯威夫特4:
目前,我更喜欢使用ProcessInfo类来知道设备是否是模拟器以及正在使用的设备类型:
if let simModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
print("yes is a simulator :\(simModelCode)")
}
但是,正如您所知道的,simModelCode并不是一个容易理解的代码,因此,如果您需要,您可以尝试查看另一个so答案,以确定当前的iPhone/设备模型,并获得一个更适合人类阅读的字符串。
达尔文在这里描述了一切。TargetConditionals: https://github.com/apple/swift-corelibs-foundation/blob/master/CoreFoundation/Base.subproj/SwiftRuntime/TargetConditionals.h
TARGET_OS_SIMULATOR—生成的代码将在模拟器下运行
使用下面的代码:
#if targetEnvironment(simulator)
// Simulator
#else
// Device
#endif
适用于Swift 4和Xcode 9.4.1