在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
这些是编译时宏,在运行时不可用。
我如何在Swift中实现同样的目标?
当前回答
斯威夫特4
现在可以使用targetEnvironment(模拟器)作为参数。
#if targetEnvironment(simulator)
// Simulator
#else
// Device
#endif
为Xcode 9.3更新
其他回答
我不知道这是否对任何人有用,但至少M1 mac的当前版本似乎没有将SIMULATOR_MODEL_IDENTIFIER传递到NSProcessInfo
我使用
BOOL isMobile = [[NSProcessInfo processInfo].environment[@"USER"] isEqual:@"mobile"];
和迅捷的对等物。这可能很脆弱,但很有效。
运行时,但比这里的大多数其他解决方案更简单:
if TARGET_OS_SIMULATOR != 0 {
// target is current running in the simulator
}
或者,你可以调用一个Objective-C helper函数来返回一个使用预处理器宏的布尔值(特别是如果你已经在你的项目中混合了)。
编辑:不是最好的解决方案,特别是在Xcode 9.3中。请看HotJard的回答
来自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
更新信息截至2018年2月20日
看起来@russbishop有一个权威的答案,使这个答案“不正确”-即使它似乎工作了很长一段时间。
检测应用程序是否正在构建的设备或模拟器在Swift
以前的回答
基于@WZW的回答和@Pang的评论,我创建了一个简单的实用结构。这个解决方案避免了@WZW的答案产生的警告。
import Foundation
struct Platform {
static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
}
使用示例:
if Platform.isSimulator {
print("Running on Simulator")
}
swift 4.1已过时。请改用#if targetEnvironment(模拟器)。源
要检测Swift中的模拟器,您可以使用构建配置:
在Swift Compiler中定义此配置- d IOS_SIMULATOR - Custom Flags >其他Swift Flags 在下拉菜单中选择Any iOS Simulator SDK
现在你可以使用这个语句来检测模拟器:
#if IOS_SIMULATOR
print("It's an iOS Simulator")
#else
print("It's a device")
#endif
你也可以扩展UIDevice类:
extension UIDevice {
var isSimulator: Bool {
#if IOS_SIMULATOR
return true
#else
return false
#endif
}
}
// Example of usage: UIDevice.current.isSimulator