【问题标题】:Retrieving Device Information React-Native iOS检索设备信息 React-Native iOS
【发布时间】:2018-08-14 15:06:00
【问题描述】:

您好,我正在尝试从 iPad 获取设备信息。我曾尝试使用https://github.com/rebeccahughes/react-native-device-info,但在我完成 pod install 之后,它完全破坏了我的解决方案。我希望至少能够获得设备的名称。我如何在不使用 NPM 模块的情况下解决这个问题,或者有人知道一个不需要引入额外依赖项的工作吗?

谢谢!

【问题讨论】:

  • 您需要一个使用本机代码提取设备相关信息的库。

标签: javascript ios reactjs react-native


【解决方案1】:

这可以使用Native Modules 轻松完成,不需要库或依赖项。

同步版本

在你的 JS 中:

import { NativeModules} from "react-native"

const DeviceInfo = NativeModules.DeviceInfo;

const deviceName = DeviceInfo.getName();

在 iOS 中: RCTDeviceInfo.h

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>

@interface RCTDeviceInfo : NSObject<RCTBridgeModule>

@end

RCTDeviceInfo.m

#import "RCTDeviceInfo.h"

@implementation RCTDeviceInfo

RCT_EXPORT_MODULE(DeviceInfo);

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getName) {
    return [[UIDevice currentDevice] name];
}

@end

异步版本

在你的 JS 中:

import { NativeModules} from "react-native"

const DeviceInfo = NativeModules.DeviceInfo;

DeviceInfo.getName().then(deviceName => {
  console.log("Current Device: "+deviceName);
}

在 iOS 中: RCTDeviceInfo.h

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>

@interface RCTDeviceInfo : NSObject<RCTBridgeModule>

@end

RCTDeviceInfo.m

#import "RCTDeviceInfo.h"

@implementation RCTDeviceInfo

RCT_EXPORT_MODULE(DeviceInfo);

RCT_EXPORT_METHOD(getName
              getName_resolver:(RCTPromiseResolveBlock)resolve
              getName_rejecter:(RCTPromiseRejectBlock)reject) {
    resolve([[UIDevice currentDevice] name]);
}

@end

【讨论】:

  • 谢谢,是的,太棒了,这是有道理的,但是当我在应用程序中尝试这个时,我得到了这个错误:Chrome 不支持在本机模块上调用同步方法。考虑提供替代方法以在调试模式下公开此方法,例如提前公开常量。”关于如何解决此问题的任何想法?
  • 如果您还想使用 chrome 调试器,则不能在本机模块中使用同步方法。我将添加另一个不会使调试器崩溃的异步版本
  • 我在我的项目或 React 库源代码中的任何地方都找不到对 RCTDataLogger.h 的引用。 React 有那个类吗?
  • @AkinWilliams 抱歉,这是我的错字。应该是#import "RCTDeviceInfo.h"
猜你喜欢
  • 2011-01-13
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2016-08-10
  • 2020-07-18
  • 2017-11-22
  • 1970-01-01
  • 2021-03-02
相关资源
最近更新 更多