Constants.h文件
#import <Foundation/Foundation.h>
extern NSString * const NotifyName1;
@interface Constants : NSObject
@end
Constants.m文件
#import "Constants.h"
NSString * const NotifyName1 = @"NotifyName1";
@implementation Constants
@end
RNIOSExportJsToReact.h文件
#import <React/RCTEventEmitter.h>
@interface RNIOSExportJsToReact : RCTEventEmitter
+ (void)emitEventWithName:(NSString *)name andPayload:(NSDictionary *)payload;
@end
RNIOSExportJsToReact.m文件
#import "RNIOSExportJsToReact.h"
#import "Constants.h"
@implementation RNIOSExportJsToReact
RCT_EXPORT_MODULE();
- (NSArray<NSString *> *)supportedEvents {
return @[NotifyName1]; //这里返回的将是你要发送的消息名的数组。
}
- (void)startObserving
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(emitEventInternal:)
name:NotifyName1
object:nil];
}
- (void)stopObserving
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)emitEventInternal:(NSNotification *)notification
{
[self sendEventWithName:NotifyName1
body:notification.userInfo];
}
+ (void)emitEventWithName:(NSString *)name andPayload:(NSDictionary *)payload
{
[[NSNotificationCenter defaultCenter] postNotificationName:name
object:self
userInfo:payload];
}
@end
native端调用:
[RNIOSExportJsToReact emitEventWithName:NotifyName1 andPayload:dict];
RN端调用:
componentDidMount(){
this.subScription = emitter.addListener('NotifyName1',(body) => {
console.log(body)
})
}
componentWillUnmount() {
this.subScription.remove()
}