Reputation: 570
I am trying to add http header to URLRequest, which I am loading in WKWebView.
I tried this code:
var urlRequest = URLRequest(url: URL(string: "url")!)
urlRequest.addValue("value", forHTTPHeaderField: "key")
self.viewerWebKit.load(urlRequest)
and also this:
var urlRequest = URLRequest(url: URL(string: "url")!)
urlRequest.setValue("value", forHTTPHeaderField: "key")
self.viewerWebKit.load(urlRequest)
But when I am printing http headers with this code:
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let headers = (navigationResponse.response as! HTTPURLResponse).allHeaderFields
for (key,value) in headers {
print("key \(key) value \(value)")
}
decisionHandler(.allow)
}
nothing is added or set. What am I doing wrong?
Upvotes: 1
Views: 2012
Reputation: 2778
URLRequest immutable so if you want to add header in that request you need to make it mutable.use this extension to add header.
extension URLRequest {
internal mutating func addHeaders() {
let mutableRequest = ((self as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!
mutableRequest.setValue("your header", forHTTPHeaderField: "key")
self = mutableRequest as URLRequest
}
}
}
Use where you want to set Header:
request.addHeaders()
Upvotes: 1
Reputation: 46
optional func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
Use this delegate function. You can find headers of request in navigationAction.request.
Upvotes: 2