iOS 原生调用 ReatNative

377 阅读1分钟

有一个RN的项目其中一个即时通讯的模块需要用原生来写所以这里面就涉及到iOS原生和RN的交互。

iOS调用RN

1.创建一个交互通信的类。

#import <React/RCTEventEmitter.h>
#import <React/RCTBridgeModule.h>
@interface RNNotification : RCTEventEmitter <RCTBridgeModule>
@end

2.在.m需注册通知,并且向rn发送消息

#import "RNNotification.h"

@implementation RNNotification

RCT_EXPORT_MODULE();

-(id)init{
  self = [super init];
  if (self) {
    /** 注册通知 */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change_tag_action:) name:@"EventReminder" object:nil];
  }
  return self;
}

/** 调用rn */
- (void)change_tag_action:(NSNotification *)notification{
  /** Name是RN监听的方法名称的 */
  [self sendEventWithName:@"EventReminder" body:notification.object];
}

/** 设置返回所监听的方法集合 */
- (NSArray<NSString *> *)supportedEvents{
  return @[@"EventReminder"];
}

@end

3.然后在RN初始化的地方初始化这个通知类,也就相当于注册通知了。不然你发通知的时候收不到消息。

- (void) viewDidLoad {
  [super viewDidLoad];
  NSURL *jsCodeLocation;
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"yanzhi"
                                               initialProperties:nil
                                                   launchOptions:nil];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  self.view = rootView;
  
  /** iOS 调用RN跳转 */
  [[RNNotification alloc] init].bridge = rootView.bridge;
}

报错: bridge is not set. This is probably because you've explicitly synthesized the bridge in %@, even though it's inherited from RCTEventEmitter.

解决方案就是直接在RN初始化的时候把bridge赋值过去