如何从 Objective-C 获取 RCTBridgeModule 实例



我目前正在参与一个 React Native 项目。目前,我尝试发送一个本地触发的事件(接收通知),然后将一些信息发送到 ReactNative 端。

我制作了我的模块:接口:

#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
#import "RCTBridgeDelegate.h"
@interface PushModule : NSObject <RCTBridgeModule>
-(void) sendNotificationInfo: (NSDictionary*)info;
@end

实现:

#import "PushModule.h"
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
@implementation PushModule
RCT_EXPORT_MODULE()
@synthesize bridge = _bridge;
-(void) sendNotificationInfo:(NSDictionary *)info {
    [bridge.eventDispatcher sendDeviceEventWithName:@"notification" body:info];
}
@end

然后我想访问它并调用我的方法:

PushModule* pushModule = [PushModule new];
[pushModule sendNotificationInfo:@{@"title": @"My Title"}];

尝试这个,桥原来是零,我从来没有在 React 中收到任何东西。我确实从Android收到了我的信息,所以ReactNative部分还可以。现在我从我查看的所有其他来源得到的,似乎我不应该自己实例化我的模块,而是让系统处理这个问题。所以问题是:这是否正确,如果是,我如何访问该实例?

我自己解决了,最终;P

我所做的是使用从rootView获得的桥初始化我的模块。因此,在 AppDelegate 中,我提取了桥:

我在界面中制作了自己的鸟卒:

@property (nonatomic, strong) RCTBridge* bridge;

在实现中:

@synthesize bridge;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSURL* jsLocation = [[RCTBundleURLProvider sharedSettings]jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsLocation moduleName:@"Metro"initialProperties:nil launchOptions:launchOptions];
    self.bridge = rootView.bridge;
    ...
}

然后,每当我想将信息发送到反应端时,我都会使用需要桥接的初始值设定项传递桥接。

PushModule* pushModule = [[PushModule alloc] initWithBridge: self.bridge];
....getting my info....
[pushModule sendNotificationInfo:notificationInfo];

所以事实证明,由于不知道/意识到rootView本身有一个桥梁,我让自己很难受。快乐的一天,可爱的编码。我希望有人从我的斗争中受益。

最新更新