Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 312
alanionita Avatar asked Jan 27 '23 19:01

alanionita


2 Answers

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.

like image 61
Pranit Harekar Avatar answered Jan 30 '23 09:01

Pranit Harekar


You can run a local React app without a server. Just use function WkWebView.loadFileURL(url, allowingReadAccessTo: url) . You can check the detailed steps to add your React app files to your xcode project in this answer.

Remember to configure your React app to use relative paths by setting "homepage": "./" in your package.json.

like image 30
noe Avatar answered Jan 30 '23 07:01

noe