Created
October 19, 2018 23:21
-
-
Save jhonsore/339b71f9ce24f5a242e4998a71a5e84f to your computer and use it in GitHub Desktop.
iOS custom native module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#FOUND ON | |
https://www.reactnative.guide/16-custom-native-modules/16.2-ios-native-module.html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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( | |
... | |
) | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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