美文网首页
Ios原生向react-native发送事件通知

Ios原生向react-native发送事件通知

作者: 康闹闹2013 | 来源:发表于2019-06-11 13:31 被阅读0次

直接上代码:

第一步:原生里边新建oc类,xxx.h

#import <React/RCTBridgeModule.h>

#import <React/RCTEventEmitter.h>

NS_ASSUME_NONNULL_BEGIN

@interfaceMySendMessageModule : RCTEventEmitter

-(void)sendMessageToRn:(NSString*)isBack;

+ (id)allocWithZone:(NSZone*)zone;

@end

NS_ASSUME_NONNULL_END

xxx.m

@implementationMySendMessageModule

//@synthesize bridge = _bridge;

RCT_EXPORT_MODULE(mySendModule)

+ (id)allocWithZone:(NSZone *)zone {

  staticMySendMessageModule *sharedInstance =nil;

  staticdispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{

    sharedInstance = [super allocWithZone:zone];

  });

  returnsharedInstance;

}

-(NSArray<NSString*> *)supportedEvents

{

  return @[@"backMessage"];

}

-(void)sendMessageToRn:(NSString *)isBack

{

  [selfsendEventWithName:@"backMessage"body:nil];

}

@end


其中:

+ (id)allocWithZone:(NSZone *)zone 

-(NSArray<NSString*> *)supportedEvents

这两个函数时必须实现的,supportedEvents里边定义了你所有要向react-native发送的消息事件。

-(void)sendMessageToRn:(NSString *)isBack,则是向react-native实际的发送消息,这个可以根据自己的需要来定义。

第二步,原生如何调用上面的发送消息的接口

在需要发送消息的地方如下使用:

 MySendMessageModule *manager = [MySendMessageModule allocWithZone:nil];

 [manager sendMessageToRn:@"yes"];

第三步:在react-native中如下使用:

import {NativeModules,NativeEventEmitter} from 'react-native'

let iOSExport =NativeModules.mySendModule;

const managerEmitter =new NativeEventEmitter(iOSExport);

const subscription = managerEmitter.addListener(

'backMessage',//原生发 送的消息事件

    (reminder) => {

//此处做你收到事件后,想做的事情

}

);

相关文章

网友评论

      本文标题:Ios原生向react-native发送事件通知

      本文链接:https://www.haomeiwen.com/subject/kczffctx.html