Create your native module (iOS)
suggest changeIntroduction
From the React Native iOS native-modules docs:
Sometimes an app needs access to a platform API, and React Native doesn’t have a corresponding module yet. Maybe you want to reuse some existing Objective-C, Swift or C++ code without having to reimplement it in JavaScript, or write some high performance, multi-threaded code such as for image processing, a database, or any number of advanced extensions.
A native module is an Objective-C class that implements the RCTBridgeModule protocol. Newer React Native versions import that header as <React/RCTBridgeModule.h> instead of the quoted path below.
Example
In your Xcode project, create a new file and select Cocoa Touch Class. Name the class NativeModuleEx, subclass NSObject, and choose Objective-C.
That creates NativeModuleEx.h and NativeModuleEx.m.
Import RCTBridgeModule.h in NativeModuleEx.h as follows:
#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
@interface NativeModuleEx : NSObject <RCTBridgeModule>
@end
In NativeModuleEx.m, add:
#import "NativeModuleEx.h"
@implementation NativeModuleEx
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(testModule:(NSString *)string )
{
NSLog(@"The string '%@' comes from JavaScript! ", string);
}
@end
RCT_EXPORT_MODULE() exposes the module to JavaScript. You can pass an optional name. If you omit it, the name matches the Objective-C class.
RCT_EXPORT_METHOD() exposes a method to JavaScript. Only methods exported with this macro are visible from JavaScript.
Call the method from JavaScript as follows:
import { NativeModules } from 'react-native';
var NativeModuleEx = NativeModules.NativeModuleEx;
NativeModuleEx.testModule('Some String !');