Skip to content

Instantly share code, notes, and snippets.

@jhonsore
Created October 19, 2018 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhonsore/339b71f9ce24f5a242e4998a71a5e84f to your computer and use it in GitHub Desktop.
Save jhonsore/339b71f9ce24f5a242e4998a71a5e84f to your computer and use it in GitHub Desktop.
iOS custom native module
#FOUND ON
https://www.reactnative.guide/16-custom-native-modules/16.2-ios-native-module.html
import React from "react";
import {
NativeModules
} from "react-native";
export default class Component extends React.Component {
componentDidMount() {
//calling native method
NativeModules.Device.getDeviceName((err ,name) => {
console.log(err, name);
});
}
return(){
render(
...
)
}
}
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
NS_ASSUME_NONNULL_BEGIN
@interface Device : RCTEventEmitter <RCTBridgeModule>
@end
NS_ASSUME_NONNULL_END
#import "Device.h"
@implementation Device
RCT_EXPORT_MODULE();
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
- (NSArray<NSString *> *)supportedEvents
{
return @[@""];
}
//exports a method getDeviceName to javascript
RCT_EXPORT_METHOD(getDeviceName:(RCTResponseSenderBlock)callback){
@try{
NSString *deviceName = [[UIDevice currentDevice] name];
callback(@[[NSNull null], deviceName]);
}
@catch(NSException *exception){
callback(@[exception.reason, [NSNull null]]);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment