LoginSignup
29
23

More than 5 years have passed since last update.

React Nativeを実機で動かす方法

Posted at

ひと通りチュートリアルをやってみていざ実機転送してみようとするとこんなエラーが出てきた。
IMG_3321.PNG

ドキュメントになかったのでしばらく悩んだけど普通にAppDelegate.mにコメントで書かれてました。

どうやらReact Nativeは処理自体はサーバで実行されているみたい。実機で動かす方法は、PCで立ち上げたサーバにアクセスする方法と、そのサーバごとアプリ内にバンドルする2つの方法が用意されているみたいです。PCで立ち上げたサーバにアクセスするのはデバッグするとき用でしょうね。

もちろんこれだと実機単体で動かせないので、その場合は OPTION 2 のサーバをアプリ内にバンドルする方法を使います。curlコマンドで出力した main.jsbundle をXcodeプロジェクトに追加してあげるとアプリ内で読み込めるようになり、実機単体で動くようになりました。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  // Loading JavaScript code - uncomment the one you want.

  // OPTION 1
  // Load from development server. Start the server from the repository root:
  //
  // $ npm start
  //
  // To run on device, change `localhost` to the IP address of your computer, and make sure your computer and
  // iOS device are on the same Wi-Fi network.
//  jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];

  // OPTION 2
  // Load from pre-bundled file on disk. To re-generate the static bundle, run
  //
  // $ curl http://localhost:8081/index.ios.bundle -o main.jsbundle
  //
  // and uncomment the next following line
  jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"AwesomeProject"
                                                   launchOptions:launchOptions];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [[UIViewController alloc] init];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

IMG_3322.PNG

29
23
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
23