在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
运行时,但比这里的大多数其他解决方案更简单:
if TARGET_OS_SIMULATOR != 0 {
// target is current running in the simulator
}
或者,你可以调用一个Objective-C helper函数来返回一个使用预处理器宏的布尔值(特别是如果你已经在你的项目中混合了)。
编辑:不是最好的解决方案,特别是在Xcode 9.3中。请看HotJard的回答
其他回答
我希望这个扩展可以派上用场。
extension UIDevice {
static var isSimulator: Bool = {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}()
}
用法:
if UIDevice.isSimulator {
print("running on simulator")
}
斯威夫特4:
目前,我更喜欢使用ProcessInfo类来知道设备是否是模拟器以及正在使用的设备类型:
if let simModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
print("yes is a simulator :\(simModelCode)")
}
但是,正如您所知道的,simModelCode并不是一个容易理解的代码,因此,如果您需要,您可以尝试查看另一个so答案,以确定当前的iPhone/设备模型,并获得一个更适合人类阅读的字符串。
运行时,但比这里的大多数其他解决方案更简单:
if TARGET_OS_SIMULATOR != 0 {
// target is current running in the simulator
}
或者,你可以调用一个Objective-C helper函数来返回一个使用预处理器宏的布尔值(特别是如果你已经在你的项目中混合了)。
编辑:不是最好的解决方案,特别是在Xcode 9.3中。请看HotJard的回答
Xcode 11, Swift 5
#if !targetEnvironment(macCatalyst)
#if targetEnvironment(simulator)
true
#else
false
#endif
#endif
来自Xcode 9.3
#if targetEnvironment(simulator)
Swift supports a new platform condition targetEnvironment with a single valid argument simulator. Conditional compilation of the form '#if targetEnvironment(simulator)' can now be used to detect when the build target is a simulator. The Swift compiler will attempt to detect, warn, and suggest the use of targetEnvironment(simulator) when evaluating platform conditions that appear to be testing for simulator environments indirectly, via the existing os() and arch() platform conditions. (SE-0190)
iOS 9+:
extension UIDevice {
static var isSimulator: Bool {
return NSProcessInfo.processInfo().environment["SIMULATOR_DEVICE_NAME"] != nil
}
}
斯威夫特3:
extension UIDevice {
static var isSimulator: Bool {
return ProcessInfo.processInfo.environment["SIMULATOR_DEVICE_NAME"] != nil
}
}
iOS 9之前:
extension UIDevice {
static var isSimulator: Bool {
return UIDevice.currentDevice().model == "iPhone Simulator"
}
}
objective - c:
@interface UIDevice (Additions)
- (BOOL)isSimulator;
@end
@implementation UIDevice (Additions)
- (BOOL)isSimulator {
if([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){9, 0, 0}]) {
return [NSProcessInfo processInfo].environment[@"SIMULATOR_DEVICE_NAME"] != nil;
} else {
return [[self model] isEqualToString:@"iPhone Simulator"];
}
}
@end