RN-iOS 原生向RN发送消息....

Posted iOSTianNan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RN-iOS 原生向RN发送消息....相关的知识,希望对你有一定的参考价值。

原生端代码
NatPushManager.h

#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTBridge.h>


@interface NatPushManager :  RCTEventEmitter <RCTBridgeModule>
@end

NatPushManager.m

#import "NatPushManager.h"
#define NATIVE_TO_RN_ONNOFIFICATION @"onNotification"
#define NATIVE_ONNOFIFICATION @"native_onNotification"
@implementation NatPushManager
  


RCT_EXPORT_MODULE();





-(NSArray*)supportedEvents 
  return@[NATIVE_TO_RN_ONNOFIFICATION];

- (void)nativeSendNotificationToRN:(NSNotification*)notification 
  NSLog(@"NativeToRN notification.userInfo = %@", notification.userInfo);
  dispatch_async(dispatch_get_main_queue(), ^
    [self sendEventWithName:NATIVE_TO_RN_ONNOFIFICATION body:notification.userInfo];
  );

- (void)startObserving 
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(nativeSendNotificationToRN:)
                                               name:NATIVE_ONNOFIFICATION
                                             object:nil];

- (void)stopObserving 
  [[NSNotificationCenter defaultCenter]removeObserver:self name:NATIVE_ONNOFIFICATION object:nil];





@end

AppDelegate.m调用

#define NATIVE_ONNOFIFICATION @"native_onNotification"

-(void)applicationWillEnterForeground:(UIApplication *)application
  [[NSNotificationCenter defaultCenter] postNotificationName:NATIVE_ONNOFIFICATION object:nil userInfo:@@"key": @"FG"];

- (void)applicationDidEnterBackground:(UIApplication *)application
  [[NSNotificationCenter defaultCenter] postNotificationName:NATIVE_ONNOFIFICATION object:nil userInfo:@@"key": @"BG"];

监听名:onNotification

RN端添加监听

      const NatPushManager = NativeModules;
      let NatPushManagerListen = new NativeEventEmitter(NatPushManager)
      NatPushManagerListen.addListener("onNotification", (res) => 
        if (res?.key === "FG") 
          start();
        
        if (res?.key === "BG") 
          pause();
        
      );

以上是关于RN-iOS 原生向RN发送消息....的主要内容,如果未能解决你的问题,请参考以下文章

RN-ios模拟器上调出中文输入法

React—Native开发之原生模块向JavaScript发送事件

RN - 封装Android原生WebView组件,实现JS获取原生消息回调及JS控制native组件

尝试向 Flutter 发送平台消息,但 FlutterJNI 与原生 C++ 分离。无法发送。频道:颤振/文本输入。响应 ID:0

据称随机获得“无权向这些 tmID 发送消息”HMS 推送服务

动态更改文本输出 - React Native