以编程方式检测app是否正在设备或模拟器上运行

eug*_*ene 54 iphone simulator detect ios

我想知道我的应用程序是否在运行时在设备或模拟器上运行.有没有办法检测到这个?

用模拟器测试蓝牙api的原因:http: //volcore.limbicsoft.com/2009/09/iphone-os-31-gamekit-pt-1-woooohooo.html

vis*_*kh7 113

#if TARGET_OS_SIMULATOR

//Simulator

#else

// Device

#endif
Run Code Online (Sandbox Code Playgroud)

请参考前面提到的问题.在编译iPhone时,Xcode会设置什么#defines

  • StackOverflow人群是否有阅读理解问题?问题是询问是否在编译时区分*运行时*!正确的答案是费尔南多塞万提斯的SIM宏,而不是这个.然而,在撰写评论时,这个错误的答案有32分,而正确的答案有3分. (9认同)
  • 请注意,这些是编译时宏,在运行时不可用. (8认同)
  • @StCredZero也许这是因为编译为在模拟器上运行的代码无法在设备上运行,反之亦然,因此最后在编译时或运行时进行检查无关紧要. (4认同)
  • @JohanKool在某些情况下确实很重要,例如如果您正在编写一个在其他人的应用程序中使用的静态库。您无法进行编译时检查,因为您的代码已经被编译。所以你的检查需要在运行时进行。举个例子:包括针对此 Xcode 8 模拟器错误的开发人员警告信息:https://forums.developer.apple.com/message/179846 (2认同)

Fer*_*tes 17

我创建了一个宏,您可以在其中指定要在括号内执行的操作,并且只有在模拟设备时才会执行这些操作.

#define SIM(x) if ([[[UIDevice currentDevice].model lowercaseString] rangeOfString:@"simulator"].location != NSNotFound){x;}
Run Code Online (Sandbox Code Playgroud)

这是这样使用的:

SIM(NSLog(@"This will only be logged if the device is simulated"));
Run Code Online (Sandbox Code Playgroud)

  • UIDevice的`model`属性不包含iOS 9中的`simulator`字样 (2认同)

Jha*_*iya 5

TARGET_IPHONE_SIMULATOR在设备上定义(但定义为false).并定义如下

#if TARGET_IPHONE_SIMULATOR
NSString * const DeviceMode = @"Simulator";
#else
NSString * const DeviceMode = @"Device";
#endif
Run Code Online (Sandbox Code Playgroud)

只是DeviceMode用来了解设备和模拟器之间的关系


hfo*_*sli 5

检查模拟器

#if TARGET_IPHONE_SIMULATOR
// Simulator
#endif
Run Code Online (Sandbox Code Playgroud)

检查设备

#if !(TARGET_IPHONE_SIMULATOR)
// Device
#endif
Run Code Online (Sandbox Code Playgroud)

检查两者

#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
Run Code Online (Sandbox Code Playgroud)

请注意,您不应该ifdef开启, TARGET_IPHONE_SIMULATOR因为它将始终定义为10.