最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Retrieving Device Information React-Native iOS - Stack Overflow

programmeradmin0浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论