Hello there,
I'm looking for a solution to navigate a URL with header's variable.
I know we can create a request and setValue with forHTTPHeaderField then use WKWebView to load it.
Here is my sample code
struct WebView: UIViewRepresentable {
let startURL: String
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
if let url = URL(string: startURL) {
var request = URLRequest(url: url)
request.setValue("yourvalue", forHTTPHeaderField: "yourHeaderVariable")
webView.navigationDelegate = context.coordinator //<<Add your delegates here
webView.uiDelegate = context.coordinator //<<Add your delegates here
webView.load(request)
}
return webView
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
{
if navigationAction.targetFrame == nil {
webView.load(navigationAction.request)
}
print(navigationAction.request.allHTTPHeaderFields)
decisionHandler(.allow)
}
}
}
This method is only able to set header variable with startURL. And there is another link in this webpage, the link doesn't include the header after I click it.
I can use allHTTPHeaderFields to show the content of http headers. And I tried to setValue in the Coordinator, the compiler said "Cannot use mutating member on immutable value: 'request' is a get-only property". I think it means this method is read-only here.
How can I do if I want to have my WKWebView can include the header variable in any links in startURL? Hope my description is clear. Thank you in advance.
My working environment: Xcode 12.5. Language: SwiftUI