ios 以编程方式检测应用程序是否正在设备或模拟器上运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5775420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically detect if app is being run on device or simulator
提问by eugene
I'd like to know whether my app is being run on device or simulator at run time. Is there a way to detect this?
我想知道我的应用程序在运行时是在设备上还是在模拟器上运行。有没有办法检测到这一点?
Reason being to test bluetooth api with simulator: http://volcore.limbicsoft.com/2009/09/iphone-os-31-gamekit-pt-1-woooohooo.html
用模拟器测试蓝牙 api 的原因:http: //volcore.limbicsoft.com/2009/09/iphone-os-31-gamekit-pt-1-wooohooo.html
回答by visakh7
#if TARGET_OS_SIMULATOR
//Simulator
#else
// Device
#endif
Pls refer this previous SO question also What #defines are set up by Xcode when compiling for iPhone
请参考这个以前的 SO 问题,当为 iPhone 编译时,Xcode 设置了什么 #defines
回答by Fernando Cervantes
I created a macro in which you can specify which actions you want to perform inside parentheses and these actions will only be performed if the device is being simulated.
我创建了一个宏,您可以在其中指定要在括号内执行的操作,并且只有在模拟设备时才会执行这些操作。
#define SIM(x) if ([[[UIDevice currentDevice].model lowercaseString] rangeOfString:@"simulator"].location != NSNotFound){x;}
This is used like this:
这是这样使用的:
SIM(NSLog(@"This will only be logged if the device is simulated"));
回答by hfossli
Check if simulator
检查模拟器
#if TARGET_IPHONE_SIMULATOR
// Simulator
#endif
Check if device
检查设备是否
#if !(TARGET_IPHONE_SIMULATOR)
// Device
#endif
Check for both
检查两者
#if TARGET_IPHONE_SIMULATOR
// Simulator
#else
// Device
#endif
Please note that you should not ifdef
on
TARGET_IPHONE_SIMULATOR
because it will always be defined to either 1
or 0
.
请注意,您不应该ifdef
打开,
TARGET_IPHONE_SIMULATOR
因为它将始终定义为1
或0
。
回答by Jhaliya
TARGET_IPHONE_SIMULATORis defined on the device (but defined to false). and defined as below
TARGET_IPHONE_SIMULATOR在设备上定义(但定义为 false)。并定义如下
#if TARGET_IPHONE_SIMULATOR
NSString * const DeviceMode = @"Simulator";
#else
NSString * const DeviceMode = @"Device";
#endif
Just use DeviceMode
to know between device and simulator
只是DeviceMode
用来了解设备和模拟器之间
回答by Julio Gorgé
You can use the TARGET_IPHONE_SIMULATORpreprocessor macro to distinguish between device and simulator targets.
您可以使用TARGET_IPHONE_SIMULATOR预处理器宏来区分设备和模拟器目标。
回答by theapache64
From XCode 9.3+ , Swift
从 XCode 9.3+ 开始,Swift
#if targetEnvironment(simulator)
//Simulator
#else
//Real device
#endif
Helps you to code against device type specific.
帮助您针对特定设备类型进行编码。
回答by Haroldo Gondim
Use this below code:
使用以下代码:
#if targetEnvironment(simulator)
// iOS Simulator
#else
// Device
#endif
Works for Swift 4
and Xcode 9.4.1
适用于Swift 4
和Xcode 9.4.1