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

问题描述 投票:55回答:8

我想知道我的应用是在运行时在设备还是模拟器上运行。有没有办法检测到这一点?

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

iphone ios simulator detect
8个回答
114
投票
#if TARGET_OS_SIMULATOR

//Simulator

#else

// Device

#endif

也请参考先前的SO问题What #defines are set up by Xcode when compiling for iPhone


18
投票

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

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

这是这样使用的:

SIM(NSLog(@"This will only be logged if the device is simulated"));

5
投票

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

#if TARGET_IPHONE_SIMULATOR
NSString * const DeviceMode = @"Simulator";
#else
NSString * const DeviceMode = @"Device";
#endif

只需使用DeviceMode即可知道设备和模拟器之间的关系>>

检查是否模拟器

#if TARGET_IPHONE_SIMULATOR
// Simulator
#endif

检查是否设备

#if !(TARGET_IPHONE_SIMULATOR)
// Device
#endif

检查两者

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

[请注意,您不应该在ifdefTARGET_IPHONE_SIMULATOR,因为它将始终定义为10

您可以使用TARGET_IPHONE_SIMULATOR预处理程序宏来区分设备目标和模拟器目标。

从XCode 9.3+开始,Swift

#if targetEnvironment(simulator)
//Simulator
#else
//Real device
#endif

帮助您针对特定的设备类型进行编码。

使用下面的代码:

#if targetEnvironment(simulator)
   // iOS Simulator
#else
   // Device
#endif

Swift 4Xcode 9.4.1的作品

[如果有人正在寻找Unity解决方案,我会这样做,这是我找到方法的唯一方法。

using System.Globalization;

public static bool IsArm() {
        return CultureInfo.InvariantCulture.CompareInfo.IndexOf(SystemInfo.processorType, "ARM", CompareOptions.IgnoreCase) >= 0;
    }

5
投票

检查是否模拟器


2
投票

您可以使用TARGET_IPHONE_SIMULATOR预处理程序宏来区分设备目标和模拟器目标。


2
投票

从XCode 9.3+开始,Swift


0
投票

使用下面的代码:


0
投票

[如果有人正在寻找Unity解决方案,我会这样做,这是我找到方法的唯一方法。

© www.soinside.com 2019 - 2024. All rights reserved.