I would like to implement a default custom SubClass of WKWebview as mentioned here:
The guide is working well and I can see the app using my CustomViewController.
Now I would like to change the properties of the WKWebViewConfiguration
,
This is failing and I am wondering, if there is a working example or implementation guide here.
this is how far I got:
//
// MyViewController.swift
// App
//
import UIKit
import Capacitor
class MyViewController: CAPBridgeViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print("MyViewController instance created.")
let webViewConfiguration = WKWebViewConfiguration()
// Add the custom web view as a subview
let customWebView = CustomWKWebView(frame: .zero, configuration: webViewConfiguration)
view.addSubview(customWebView)
webViewConfiguration.setURLSchemeHandler(CustomRequestInterceptor(), forURLScheme: "customScheme")
}
override func instanceDescriptor() -> InstanceDescriptor {
let descriptor = super.instanceDescriptor()
// add custom settings here
return descriptor
}
}
//
// CustomRequestInterceptor.swift
// App
//
//
import WebKit
class CustomRequestInterceptor: NSObject, WKURLSchemeHandler {
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
// Intercept and modify the request here
print("CustomRequestInterceptor instance created")
var request = urlSchemeTask.request
print("CustomRequestInterceptor request", request)
if let url = request.url, url.scheme == "customScheme" || url.scheme == "https" {
// Add your cookie header here
print("CustomRequestInterceptor url", url)
if var headers = request.allHTTPHeaderFields {
headers["Cookie"] = "your-cookie-data-here"
request.allHTTPHeaderFields = headers
}
// You need to create a response and call didReceiveResponse
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)!
urlSchemeTask.didReceive(response)
// urlSchemeTask.didReceive(urlSchemeTask.request)
// You should also call urlSchemeTask.didFinish() once the task is completed
urlSchemeTask.didFinish()
} else {
// Handle errors if necessary
urlSchemeTask.didFailWithError(NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil))
}
}
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
// Handle cleanup if necessary
}
}
Within the capacitor application I have some URLs which want to request
customScheme://somefolder/somefile.someExtension
I would expect to have a log with
“CustomRequestInterceptor instance created” but this does not appear.
Is there a recommended implementation for changing the WKWebViewConfiguration
for Capacitors Webview?