2016-07-26 64 views
1

我对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两次。

任何帮助表示赞赏。

+0

什么时候创建被调用的方法?这可能是它调用得太早,应用程序的RN部分尚未初始化? – rmevans9

+0

@ rmevans9我已更新我的问题 –

+0

难道你不能让getUsername调用只需调用第三方并通过桥将getUsername导出到JavaScript,然后调用getUsername?当我在一台机器上时,我会链接一些关于如何执行此操作的文档。 – rmevans9

回答

1

你可以不用试图把它放在iOS端的初始启动代码中,而是将它放在一个本地模块中,该模块导出一个函数以返回信息。请参阅React Natives官方文档:https://facebook.github.io/react-native/docs/native-modules-ios.html

+0

谢谢你的建议。我实际上正在考虑这样做,但对于我所需要的“只发送一个对象到JavaScript”我觉得没有必要。是不是有一个更简单的方法来“桥接”它,而不是两次调用“rootView”? –

相关问题