从 WKWebview 检索 HTTP 响应标头
Posted
技术标签:
【中文标题】从 WKWebview 检索 HTTP 响应标头【英文标题】:Retrieve HTTP response headers from WKWebview 【发布时间】:2016-12-13 19:05:44 【问题描述】:我需要从WKWebview
的请求中读取响应HTTP 标头。我需要根据服务器发送的某些自定义标头执行自定义。无法在响应数据中添加此信息。
我在文档和以前的问题中都找不到任何条目。有什么办法吗?
【问题讨论】:
【参考方案1】:您似乎可以从WKNavigationDelegate
方法webView:decidePolicyFor:decisionHandler:
访问响应。
设置一些对象为WKWebView
的navigationDelegate
,并添加这个方法:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
NSDictionary *headers = ((NSHTTPURLResponse *)navigationResponse.response).allHeaderFields;
decisionHandler(WKNavigationResponsePolicyAllow);
【讨论】:
【参考方案2】:NobodyNada 回答的 Swift 3.1、4 和 5 版本:
没有强制施法
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
if let response = navigationResponse.response as? HTTPURLResponse
let headers = response.allHeaderFields
//do something with headers
decisionHandler(.allow)
强制施法:
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
let headers = (navigationResponse.response as! HTTPURLResponse).allHeaderFields
//do something with headers
decisionHandler(.allow)
【讨论】:
【参考方案3】:Swift 4.2 Answers with response.
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
let response = navigationResponse.response as? HTTPURLResponse
decisionHandler(.allow)
【讨论】:
【参考方案4】:您可以从委托方法中检索(WKNavigationResponse*)navigationResponse
。您可以从 navigationResponse 对象中获取响应本身:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
【讨论】:
以上是关于从 WKWebview 检索 HTTP 响应标头的主要内容,如果未能解决你的问题,请参考以下文章