且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在UIWebView上获取HTTP响应标头

更新时间:2023-10-27 09:52:10

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 a request
  • check that the request actually has a NSCachedURLResponse
  • 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)
            }
        }
    }
}