Skip to content

Instantly share code, notes, and snippets.

@michaelenger
Created February 25, 2021 17:12
Show Gist options
  • Save michaelenger/fd394865295320645ed0d1ded9675654 to your computer and use it in GitHub Desktop.
Save michaelenger/fd394865295320645ed0d1ded9675654 to your computer and use it in GitHub Desktop.
import Swifter
import SwiftUI
import WebKit
struct WebView: UIViewRepresentable {
class NavigationDelegate: NSObject, WKNavigationDelegate {
/// Handle a failed navigation.
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("ERROR:", error)
}
/// Handle a successful navigation (a response was received).
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
print("RESPONSE:", navigationResponse)
decisionHandler(.allow) // allow everything
}
}
/// Need to keep a reference to the delegate outside the WebView so it doesn't get deallocated.
let navigationDelegate: NavigationDelegate
let request: URLRequest
var server: HttpServer
init() {
self.navigationDelegate = NavigationDelegate()
self.request = URLRequest(url: URL(string: "http://0.0.0.0:8086/testing.html")!)
/// Setup a server which just provides files. The files will be read
/// from the computer's file system so this won't work if you're
/// running in on an iOS device.
self.server = HttpServer()
self.server["/:path"] = shareFilesFromDirectory("/full/path/to/directory")
do {
try self.server.start(8086, forceIPv4: true)
print("Server started on port \(try self.server.port())")
} catch {
print("Server start error: \(error)")
}
}
func makeUIView(context: UIViewRepresentableContext<WebView>) -> WKWebView {
let webView = WKWebView()
webView.navigationDelegate = navigationDelegate
return webView
}
func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<WebView>) {
uiView.load(request)
}
}
struct WebView_Previews: PreviewProvider {
static var previews: some View {
WebView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment