正如问题所述,我主要想知道我的代码是否在模拟器中运行,但也有兴趣知道正在运行或正在模拟的特定iphone版本。

编辑:我在问题名称中添加了“以编程方式”这个词。我的问题的要点是能够动态包括/排除代码取决于哪个版本/模拟器正在运行,所以我真的在寻找像一个预处理程序指令,可以为我提供这个信息。


当前回答

用swift:

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

从检测应用程序是否正在构建的设备或模拟器在Swift

其他回答

Swift现在有了更好的方式。

从Xcode 9.3及更新版本开始,你可以使用#if targetEnvironment(模拟器)来检查。

#if targetEnvironment(simulator)
//Your simulator code
#endif

在Swift 4.2 (Xcode 10)中,我们可以做到这一点

#if targetEnvironment(simulator)
  //simulator code
#else 
  #warning("Not compiling for simulator")
#endif

所有这些答案都很好,但它在某种程度上让像我这样的新手感到困惑,因为它没有阐明编译检查和运行时检查。预处理器在编译之前,但我们应该更清楚

这篇博客文章展示了如何检测iPhone模拟器?很明显

运行时

首先,让我们简单讨论一下。UIDevice已经为您提供了有关设备的信息

[[UIDevice currentDevice] model]

将根据应用程序运行的位置返回“iPhone模拟器”或“iPhone”。

编译时

但是,您需要的是使用编译时定义。为什么?因为你严格编译你的应用程序,要么在模拟器中运行,要么在设备上运行。苹果做了一个叫做TARGET_IPHONE_SIMULATOR的定义。让我们看一下代码:

#if TARGET_IPHONE_SIMULATOR

NSLog(@"Running in Simulator - no app store or giro");

#endif

如果没有效果,试试这个

public struct Platform {

    public static var isSimulator: Bool {
        return TARGET_OS_SIMULATOR != 0 // Use this line in Xcode 7 or newer
    }

}

///如果它的模拟器不是设备,则返回true

public static var isSimulator: Bool {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        return true
    #else
        return false
    #endif
}