Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert iOS react native template to swift?

I have been reading about react native and decided to give it a try, i am fairly experienced in Swift but never tried out objective c so i would like to convert the template project to use AppDelegate.swift

I followed the solution in this accepted answer: React Native app purely in Swift, but all i have is a black screen when i run the project

Does anyone knows how can i convert the template to Swift? Can i call swift code directly from React Native without any bridge header?

I am running React Native 0.52 btw

like image 402
Steve Avatar asked Jan 09 '18 12:01

Steve


1 Answers

So after several tries i found out how to make it work with React Native 0.52

1 - Delete AppDelegate.m, AppDelegate.h and main.m

2 - Create a new AppDelegate.swift and when it asks if you would like to create an Objective-C bridge header just say "Yes"

3 - Copy the following to your Bridging-Header.h file:

#import <React/RCTBridgeModule.h>
#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTRootView.h>
#import <React/RCTUtils.h>
#import <React/RCTConvert.h>
#import <React/RCTBundleURLProvider.h>

4 - Use the following code in your AppDelegate.swift file and edit the project name:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var bridge: RCTBridge!

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let jsCodeLocation: URL

    jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index", fallbackResource:nil)
    let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "YOUR-PROJECT-NAME", initialProperties: nil, launchOptions: launchOptions)
    let rootViewController = UIViewController()
    rootViewController.view = rootView

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = rootViewController
    self.window?.makeKeyAndVisible()

    return true
  }
}

5 - Don´t forget to replace "YOUR-PROJECT-NAME" by your actual project name

6 - Run et voilà! Happy coding :)

like image 71
Steve Avatar answered Oct 24 '22 05:10

Steve