Reputation: 177
Hey I am trying to get device information from an iPad. I have tried using https://github.com/rebeccahughes/react-native-device-info but after I do pod install it completely 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!
Upvotes: 3
Views: 11842
Reputation: 3728
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
Upvotes: 4