在Objective-C中,我们可以使用宏知道应用程序是为设备还是模拟器构建的:

#if TARGET_IPHONE_SIMULATOR
    // Simulator
#else
    // Device
#endif

这些是编译时宏,在运行时不可用。

我如何在Swift中实现同样的目标?


当前回答

来自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

其他回答

在Xcode 7.2(以及更早的版本,但我还没有测试过多少)中,你可以为“任何iOS模拟器”设置一个平台特定的构建标志“-D TARGET_IPHONE_SIMULATOR”。

查看“Swift Compiler - Customer Flags”下的项目构建设置,然后在“Other Swift Flags”中设置标志。当您将鼠标悬停在构建配置上时,可以通过单击“加号”图标来设置特定于平台的标志。

这样做有几个好处:1)你可以在Swift和Objective-C代码中使用相同的条件测试(“#if TARGET_IPHONE_SIMULATOR”)。2)你可以编译出只适用于每个版本的变量。

Xcode构建设置截图

更新信息截至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 3中使用了下面的代码

if TARGET_IPHONE_SIMULATOR == 1 {
    //simulator
} else {
    //device
}

斯威夫特5.2.4 Xcode 11.7


 #if targetEnvironment(simulator)

 #endif

从Swift 1.0开始,对我来说有用的是检查除了arm之外的架构:

#if arch(i386) || arch(x86_64)

     //simulator
#else 
     //device

#endif