首页 文章

React Native - 将数据从本机发送到javascript /桥接

提问于
浏览
1

我是React Native(iOS)的新手,我已经阅读了很多关于Bridging的内容,但是我似乎无法使其工作 .

我需要能够从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:

我找到了一个解决方法,但我没有't think it'有效,因为我打电话给 RCTRootView 两次 . 首先使用 initialProperties nil加载应用程序,如下所示:

- (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];

}

而且当我第二次检索UserName时,我会像这样更新 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 .

任何帮助表示赞赏 .

1 回答

相关问题