react-native-eval
react-native-eval copied to clipboard
Works only when a React-Native view is displayed (iOS)
I am trying to run a JavaScript function from native code on iOS. It works properly when the current view is a React Native view, but it does not work when the current view is a native one. Is there any way to make it work?
I am using the package version from master, with version 0.39 of React Native.
Hm, that's weird, I've been using react-native-eval exactly like that - having native view on a top. Let me check
Yep, was able to reproduce, will check it during weekend, thanks
Figured it out. The problem is that you need to save RCTRootView somewhere, otherwise garbage collector will reset it and RN wouldn't be initialized. Here example AppDelegate code:
#import "AppDelegate.h"
#import "RCTBundleURLProvider.h"
#import "RCTRootView.h"
#import "RNMEvaluator.h"
@implementation AppDelegate
{
RCTRootView* rootView; // Save it as an instance variable for example
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"app"
initialProperties:nil
launchOptions:launchOptions];
// now as we saved rootView we can start calling RNMEvaluator
[RNMEvaluator callSyncFunction:rootView.bridge
name:@"Math.pow"
args:@[@2,@2]
cb:^(NSString *error, id returnValue) {
if (error)
NSLog(@"Error occured: %@", error);
else
NSLog(@"Function returned: %@", returnValue);
}];
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];
// Or you will get the same if you assing it as a view to some view controller
//rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;
}
@end
I will fix README documentation and mention this issue there. Thank you!
Thank you very much. Looking forward to try this on Monday!
It works indeed, thank you!