在一个Obj-C iOS应用程序中,我可以使用#if(TARGET_IPHONE_SIMULATOR)编写模拟器代码.
在反应本地我可以使用:
if (__DEV__) {
.. do something special
}
检测开发模式.
我们可以使用Platform.OS ===’ios’来检测平台(Android / iOS).
查看更多信息Platform Docs
但是如何检测应用程序是否在模拟器中运行?
我问的原因是我的应用程序使用相机扫描条形码,这在iOS模拟器中不受支持.
解决方法
我可以想到的最简单的解决方案是将这个参数作为一个反应组件属性传递,而不需要创建本机模块(或修改一个原始模块).
在您的AppDelegate中,RCTRootView初始化的地方,您会检查它是否像在常规iOS应用程序中一样;然后将此信息传递给反应根视图作为其initialProperties:
BOOL isSimulator = NO;
#if TARGET_IPHONE_SIMULATOR
isSimulator = YES;
#endif
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"ReactDemo"
initialProperties:@{@"isSimulator": @(isSimulator)}
launchOptions:launchOptions];
现在您可以通过您的反应组件的道具在JavaScript中访问它:
this.props.isSimulator
在Android上,在您的MainActivity中,扩展了ReactActivity,您可以使用类似的方法:
public boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unkNown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| "google_sdk".equals(Build.PRODUCT);
}
@Override
protected Bundle getLaunchOptions() {
Bundle opts = new Bundle();
opts.putBoolean("isEmulator",isEmulator());
return opts;
}