在Obj-C iOS应用程序中,我可以使用#if (TARGET_IPHONE_SIMULATOR)
编写仅模拟器代码。
在本地反应我可以使用:
if (__DEV__) {
.. do something special
}
..检测开发模式。
我们可以使用Platform.OS === 'ios'
来检测平台(Android / iOS)。有关更多信息,请参阅此处Platform Docs
但是我们如何检测应用程序是否在模拟器中运行?
我问的原因是我的应用程序使用相机扫描条形码,这在iOS模拟器中不受支持。
您可以使用react-native-device-info轻松完成此操作,如下所示:
import DeviceInfo from 'react-native-device-info'
isSimulator() {
return DeviceInfo.isEmulator();
},
我能想到的最简单的解决方案是,不需要创建本机模块(或修改现有模块),而是将此参数作为反应组件属性传递。
在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];
现在,您可以通过您的react组件的props在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;
}
如果您正在构建CRNA / Expo应用程序,则可以使用Expo.Constants.isDevice
https://docs.expo.io/versions/latest/sdk/constants/#constantsisdevice
import { Constants } from 'expo'
//....
console.log(Constants.isDevice) // => false if simulator
使用react-native-device-info,您可以获得以下数据(在模拟器上执行):
getUniqueID: DB71DCB5-6BB0-497B-BE9E-A02BCC1235B7
getInstanceID: undefined
getDeviceId: x86_64
getManufacturer: Apple
getModel: Simulator
getBrand: Apple
getSystemName: iOS
getSystemVersion: 10.1
getBundleId: org.reactjs.native.example.project
getBuildNumber: 1
getVersion: 1.0
getReadableVersion: 1.0.1
getDeviceName:MacBook Pro
getUserAgent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72
getDeviceLocale: en
getDeviceCountry: US
getTimezone: America/Panama
isEmulator: true
isTablet: false
目前,没有任何方法可以查看您是否在JS中使用模拟器运行。
我建议添加条件TARGET_IPHONE_SIMULATOR
来检查您的本机代码(如果您编写了自己的模块)。或者使用第三方模块,如果在模拟器中不渲染相机...即:react-native-camera:https://github.com/lwansbrough/react-native-camera/search?utf8=%E2%9C%93&q=TARGET_IPHONE_SIMULATOR