iOS 原生调用 ReatNative

本文详细介绍了如何在iOS原生环境中调用React Native组件,通过创建通信类、注册通知及在RN初始化时设置桥接,实现iOS与RN的交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有一个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赋值过去

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值