我對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