2

I would like to get the iOS device name using Native Modules and without using an external library.

According to React Native's documentation, "React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events". However, the documentation also explains that you can export constants to JavaScript without doing a round-trip from JS to Objective-C.

Is there a way to export a constant from a native module with the device name/model as a value without having to use a callback?

colado
  • 307
  • 4
  • 13

1 Answers1

0

You can create the header file as shown below:

// RCTDeviceInfo.h

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

@interface RCTDeviceInfo : NSObject<RCTBridgeModule>

@end

Then to export it you can do :

//RCTDeviceInfo.m 

#import "RCTDataLogger.h"

@implementation RCTDeviceInfo

RCT_EXPORT_MODULE(DeviceInfo);

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

@end

Then synchronously on the Javascript side you can do the following:

import { NativeModules} from "react-native"

const DeviceInfo = NativeModules.DeviceInfo;

const deviceName = DeviceInfo.getName();

You can read more from the official docs here

Felix Too
  • 11,614
  • 5
  • 24
  • 25