IOS原生模块向ReactNative发送事件消息

IOS原生模块向ReactNative发送事件消息

标签(空格分隔): ReactNative


IOS原生模块向ReactNative发送事件消息

创建一个OC类EventEmitterManager 继承自RCTEventEmitter

EventEmitterManager.h

#import 
#import 

@interface EventEmitterManager : RCTEventEmitter 
+ (id)allocWithZone:(NSZone *)zone;
- (void)sendNoticeWithEventName:(NSString *)eventName Dict:(NSDictionary *)dict;
@end

EventEmitterManager.m

#import "EventEmitterManager.h"
#import 
#import 

@implementation EventEmitterManager{
  bool hasListeners;
}

RCT_EXPORT_MODULE();

+ (id)allocWithZone:(NSZone *)zone {
  static EventEmitterManager *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [super allocWithZone:zone];
  });
  return sharedInstance;
}

- (NSArray *)supportedEvents
{
  return @[@"HttpResult"];
}

// 在添加第一个监听函数时触发
-(void)startObserving {
  hasListeners = YES;
}
// 取消监听时触发
-(void)stopObserving {
  hasListeners = NO;
}

- (void)sendNoticeWithEventName:(NSString *)eventName Dict:(NSDictionary *)dict{
  if(hasListeners){
    [self sendEventWithName:eventName body:dict];
  }
}

@end

OC对应的操作中使用

#import "EventEmitterManager.h"

EventEmitterManager *manager = [EventEmitterManager allocWithZone:nil];
[manager sendNoticeWithEventName:@"HttpResult" Dict:@{@"code":@"0"}];

RN中添加对应的监听

import {NativeEventEmitter, NativeModules} from 'react-native'
const {EventEmitterManager} = NativeModules;
const tempEventEmitterManager = new NativeEventEmitter(EventEmitterManager);
const subscription = tempEventEmitterManager.addListener(
    'HttpResult',
    (data)=>console.log({
        test:'++++++++++',
        data:data
    })
)

整个监听过程

    1. IOS中设置监听事件
    1. RN中添加对应的观察者
    1. IOS中发送对应的监听事件
    1. 消息通知中心发送消息给所有RN中的观察者

参考资料

  • 原生模块-给Javascript发送事件
  • RCTEventEmitter bridge is not set ->Liqiankun commented on 10 Oct

你可能感兴趣的:(IOS原生模块向ReactNative发送事件消息)