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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With