Search code examples
javascriptreactjswebviewwkwebview

Loading a local React app inside WKWebView iOS


I've built a site in React and would want to use the build files inside of the iOS WKWebView.


Follow-up

In order to run a React build folder it must be served so currently the only way to achieve this is to build a server inside the iOS app, serve the React build files, and load the local url in the WKWebView.

The best option I've found for the server is https://criollo.io/#getting-started.

Why is the best?

  • Work for both Objective-C and Swift codebases
  • Easy to use documentation
  • Strong support from the developer

Solution

  • You don't necessarily need to build react app and then load those files locally. It works but the better way is to start your local server i.e. yarn start and then specify your url (normally http://localhost:3000/, might differ according to your setup) to load in the WKWebView like this,

        var webView: WKWebView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let configuration = WKWebViewConfiguration()
            // (optional) your configuration 
            webView = WKWebView(frame: .zero, configuration:configuration)
            view = webView
    
            let url = URL(string: "http://localhost:3000")!
            let request = URLRequest(url: url)
            webView.load(request)
        }
    

    Since your server loads files via http, App Transport Security of iOS will block it. It only allows files to be loaded via https protocol. In order to allow ATS to load via http you need to add exception for localhost or 127.0.0.1 or whichever local ipaddr your server is running on. To do that, open info.plist as source code and paste following,

    <key>NSAppTransportSecurity</key>  
    <dict>  
        <key>NSExceptionDomains</key>  
        <dict>  
            <key>127.0.0.1</key>  
            <dict>  
                <key>NSExceptionAllowsInsecureHTTPLoads</key>  
                <true/>  
            </dict>  
            <key>localhost</key>  
            <dict>  
                <key>NSExceptionAllowsInsecureHTTPLoads</key>  
                <true/>  
            </dict>  
        </dict>  
    </dict> 
    

    Now you should be able to access your React app in WKWebView.