iOS-无法添加URLRequest的http标头

时间:2018-10-25 13:26:23

标签: ios swift url request wkwebview

我正在尝试将HTTP标头添加到URLRequest,并将其加载到WKWebView中。

我尝试了以下代码:

    var urlRequest = URLRequest(url: URL(string: "url")!)
    urlRequest.addValue("value", forHTTPHeaderField: "key")
    self.viewerWebKit.load(urlRequest)

还有这个:

    var urlRequest = URLRequest(url: URL(string: "url")!)
    urlRequest.setValue("value", forHTTPHeaderField: "key")
    self.viewerWebKit.load(urlRequest)

但是当我使用以下代码打印http标头时:

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)
}

未添加或设置任何内容。我在做什么错了?

2 个答案:

答案 0 :(得分:1)

optional func webView(_ webView: WKWebView, 
  decidePolicyFor navigationAction: WKNavigationAction, 
  decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

使用此委托函数。您可以在navigationAction.request中找到请求的标头。

答案 1 :(得分:1)

URLRequest 是不可变的,因此,如果要在该请求中添加标头,则需要使其可变。请使用此扩展名添加标头。

extension URLRequest {

internal mutating func addHeaders() {

        let mutableRequest = ((self as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!


            mutableRequest.setValue("your header", forHTTPHeaderField: "key")
            self = mutableRequest as URLRequest

        }
    }

}

在您要设置标题的地方使用:

request.addHeaders()