我对React Native(iOS)非常陌生,并且已经阅读了很多关于桥接的内容,但是我似乎无法使其工作。React Native - 从本地发送数据到JavaScript /桥接
我需要能够从AppDelegate发送一个对象/字符串到JavaScript。我的AppDelegate返回一个UserName,它是由AppDelegate中的一个我的方法中的本地代码检索的。
我试图AppDelegate.m
使用#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
然后
@synthesize bridge = _bridge;
和我的方法
NSString *eventName = notification.userInfo[@"name"];
[self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
body:@{@"name": eventName}];
但没有上述工程和内部我得到错误。我还需要为AppDelegate.h
做些什么吗?
任何人都可以帮我吗?将数据从本地发送到JavaScript的最简单方法是什么?
UPDATE:
我找到了一个解决办法,但我不认为是我打电话RCTRootView
两次是有效的。先用initialProperties
无加载应用程序,就像这样:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"myApp"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
[self getUsername];
}
以及当我找回用户名我第二次再更新initialProperties
这样的:
-(void) getUsername {
//3rd party code to retrieve the username
NSString *username = username
NSURL *jsCodeLocation;
jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:jsCodeLocation moduleProvider:nil launchOptions:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:@"myApp"
initialProperties: @{@"username" : username}];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
}
这样做上面我的方式”然后就可以在JavaScript中通过this.props
发送和接收用户名。
但就像我说的,我不确定这是一种有效的方式,因为我打电话给RCTRootView
两次。
任何帮助表示赞赏。
什么时候创建被调用的方法?这可能是它调用得太早,应用程序的RN部分尚未初始化? – rmevans9
@ rmevans9我已更新我的问题 –
难道你不能让getUsername调用只需调用第三方并通过桥将getUsername导出到JavaScript,然后调用getUsername?当我在一台机器上时,我会链接一些关于如何执行此操作的文档。 – rmevans9