在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
达尔文在这里描述了一切。TargetConditionals: https://github.com/apple/swift-corelibs-foundation/blob/master/CoreFoundation/Base.subproj/SwiftRuntime/TargetConditionals.h
TARGET_OS_SIMULATOR—生成的代码将在模拟器下运行
其他回答
在现代系统中:
#if targetEnvironment(simulator)
// sim
#else
// device
#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
TARGET_IPHONE_SIMULATOR在iOS 9中已弃用。TARGET_OS_SIMULATOR是替换。TARGET_OS_EMBEDDED也是可用的。
从targetconditions .h:
#如果定义(__GNUC__) & &(定义(__APPLE_CPP__) | |定义(__APPLE_CC__) | | (__MACOS_CLASSIC__)定义) …… #定义TARGET_OS_SIMULATOR 0 #定义TARGET_OS_EMBEDDED #定义TARGET_IPHONE_SIMULATOR TARGET_OS_SIMULATOR /* deprecated */ #定义TARGET_OS_NANO TARGET_OS_WATCH
我希望这个扩展可以派上用场。
extension UIDevice {
static var isSimulator: Bool = {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}()
}
用法:
if UIDevice.isSimulator {
print("running on simulator")
}
除了其他答案。
在Objective-c中,确保你包含了TargetConditionals。
# include < TargetConditionals.h >
在使用TARGET_OS_SIMULATOR之前。