在UIWebView上获取HTTP响应标头 [英] Get HTTP Response header on UIWebView
本文介绍了在UIWebView上获取HTTP响应标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从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
指针和期权
:
Swift is more stringent ; you want to protect yourself against nil
pointers and optionals
:
- 检查
webView
实际上是否有请求
- 检查
请求
实际上是否有NSCachedURLResponse
- 类型 - 检查对
NSHTTPURLResponse的反应
- check that the
webView
actually has arequest
- check that the
request
actually has aNSCachedURLResponse
- type-check the response against
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响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文