2016-07-26 43 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」? –

相關問題