Sometimes console.log shows in log-ios sometimes it doesn't

后端 未结 2 1694
栀梦
栀梦 2021-01-02 20:32

I have run react-native start in one terminal, and then react-native ios-run in another. My initial console.log rarely show, sometimes

2条回答
  •  不知归路
    2021-01-02 20:48

    i found that the JavascriptCore engine won't automatically redirect the console.log to either XCode output panel or the system builtin Console.App, not to mention the self-broken log-ios command.

    the only way to see console.log without remote debugging in browser is redirect(bind) it ourselves:

    //Add this headers
    #import 
    #import 
    #import 
    ...
    ...
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    
      NSURL *jsCodeLocation;
      ...
      ...
      [self.window makeKeyAndVisible];
    
    
      ::sleep(2); //<---!!!!!see below
    
      JSGlobalContextRef globalContext = rootView.bridge.jsContextRef;
      JSContext *context = [JSC_JSContext(globalContext) contextWithJSGlobalContextRef:globalContext];
      context[@"console"][@"log"] = ^(NSString *message) {
        NSLog(@"Javascript log: %@",message);
      };
      return YES;
    }
    

    Caution: the JSContext within reactInstance is created in another thread, I don't know how to get the loaded event(in only my project, since i don't like to modify the react-native engine), just wait sometime here for testing purpose.

提交回复
热议问题