admin管理员组

文章数量:1335552

Hey I am trying to get device information from an iPad. I have tried using but after I do pod install it pletely break my solution. Id like to be able to at least get the device's name. How can I go about this without using an NPM module or does anyone know of one that works that doest have to pull in extra dependencies?

Thanks!

Hey I am trying to get device information from an iPad. I have tried using https://github./rebeccahughes/react-native-device-info but after I do pod install it pletely break my solution. Id like to be able to at least get the device's name. How can I go about this without using an NPM module or does anyone know of one that works that doest have to pull in extra dependencies?

Thanks!

Share Improve this question asked Aug 14, 2018 at 15:06 user3637804user3637804 1772 gold badges2 silver badges10 bronze badges 1
  • You need a library that uses native code to extract device-related information. – Dan Commented Aug 14, 2018 at 16:26
Add a ment  | 

1 Answer 1

Reset to default 4

This can be done easily using Native Modules, no libraries or dependencies required.

Synchronous version

in your JS:

import { NativeModules} from "react-native"

const DeviceInfo = NativeModules.DeviceInfo;

const deviceName = DeviceInfo.getName();

in 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

Asynchronous version

in your JS:

import { NativeModules} from "react-native"

const DeviceInfo = NativeModules.DeviceInfo;

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

in 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

本文标签: javascriptRetrieving Device Information ReactNative iOSStack Overflow