React Native:如何检测我的代码是否在模拟器中运行?

问题描述 投票:28回答:5

在Obj-C iOS应用程序中,我可以使用#if (TARGET_IPHONE_SIMULATOR)编写仅模拟器代码。

在本地反应我可以使用:

if (__DEV__) {
 .. do something special
}

..检测开发模式。

我们可以使用Platform.OS === 'ios'来检测平台(Android / iOS)。有关更多信息,请参阅此处Platform Docs

但是我们如何检测应用程序是否在模拟器中运行?

我问的原因是我的应用程序使用相机扫描条形码,这在iOS模拟器中不受支持。

android ios react-native
5个回答
52
投票

您可以使用react-native-device-info轻松完成此操作,如下所示:

import DeviceInfo from 'react-native-device-info'

isSimulator() {
  return DeviceInfo.isEmulator();
},

21
投票

我能想到的最简单的解决方案是,不需要创建本机模块(或修改现有模块),而是将此参数作为反应组件属性传递。

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上,在你扩展MainActivityReactActivity中你可以使用类似的方法:

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;
}

10
投票

如果您正在构建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

6
投票

使用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

1
投票

目前,没有任何方法可以查看您是否在JS中使用模拟器运行。

我建议添加条件TARGET_IPHONE_SIMULATOR来检查您的本机代码(如果您编写了自己的模块)。或者使用第三方模块,如果在模拟器中不渲染相机...即:react-native-camera:https://github.com/lwansbrough/react-native-camera/search?utf8=%E2%9C%93&q=TARGET_IPHONE_SIMULATOR

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