如何从 WebView 获取 HTTP 标头响应?我找到了半解决方案在 Stackoverflow,但它是用 Objective-C 编写的,无法将其转换为 Swift (我已经尝试过使用我糟糕的 Obj-C 知识).
How can I get HTTP headers response from WebView? I've found semi-solutions at Stackoverflow, but it's written on Objective-C and can't convert it to Swift (I've tried with my poor Obj-C knowledge).
Objective-C 代码:
Objective-C code:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSCachedURLResponse *resp = [[NSURLCache sharedURLCache] cachedResponseForRequest:webView.request];
NSLog(@"%@",[(NSHTTPURLResponse*)resp.response allHeaderFields]);
}
Swift
Swift 更严格;你想保护自己免受 nil
指针和 optionals
:
Swift is more stringent ; you want to protect yourself against nil
pointers and optionals
:
webView
是否确实有 request
request
是否确实有 NSCachedURLResponse
NSHTTPURLResponse
webView
actually has a request
request
actually has a NSCachedURLResponse
NSHTTPURLResponse
func webViewDidFinishLoad(webView: UIWebView) {
if let request = webView.request {
if let resp = NSURLCache.sharedURLCache().cachedResponseForRequest(request) {
if let response = resp.response as? NSHTTPURLResponse {
print(response.allHeaderFields)
}
}
}
}
这篇关于在 UIWebView 上获取 HTTP 响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!