【问题标题】:UIWebView request.response = nil IssueUIWebView request.response = nil 问题
【发布时间】:2016-08-18 06:56:46
【问题描述】:

我在webViewDidFinishLoad 中遇到了来自UIWebView 的问题,我得到了

if let urlResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(webView.request!)?.response {

    if (urlResponse as! NSHTTPURLResponse).statusCode == 200 {

    }
}

作为nil,所以在显示正文时我无法检查状态代码。请问问题出在哪里?我可以从服务器端做些什么吗?

编辑:从其他请求中我可以看到响应。

【问题讨论】:

  • 您的网址已加载意味着是否可见
  • @Anbu.Karthik 对不起,我没听懂你,你说的可见或不可见是什么意思?
  • 总是这样吗?还是仅在某个 URL 上?
  • @JulienQuere 它发生在某些 URL 上
  • 好的,我想我明白这个问题了。您正在检查NSURLCache.sharedURLCache().cachedResponseForRequest,但是如果没有缓存答案怎么办?如果服务器明确表示:“不缓存此响应”,则页面将显示,但不缓存。

标签: ios swift webview nsurlcache


【解决方案1】:

所以,我认为这是因为您正在检查 NSURLCache 以获取您的请求响应。但有时,您的页面可以显示,但不能缓存。事实上,服务器可以这样响应:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

它说:“你绝对不应该缓存我的回复”。作为一个好公民,iOS 不会:)。因此,我们必须使用不同的方式来获取服务器响应。我认为最好的解决方案是使用NSURLSession 提出您的请求,下载内容并将其转发到您的网页视图。发出请求后,您将能够访问答案是完成处理程序。这是您可以执行的操作的示例:

func loadURL(url: NSURL!) {
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)

    let muableRequest = NSMutableURLRequest(URL: url)
    muableRequest.setValue("WhateverYouWant", forHTTPHeaderField: "x-YourHeaderField")

    let task = session.dataTaskWithRequest(muableRequest) { (data, response, error) in

        guard error == nil else {
            print("We have an error :( \(error)")
            // Here, you have to handle the error ...
            return
        }

        if let response = response {
            var mimeType = ""
            if response.MIMEType != nil {
                mimeType = response.MIMEType!
            }

            var encoding = ""
            if response.textEncodingName != nil {
                encoding = response.textEncodingName!
            }

            if let httpResponse = response as? NSHTTPURLResponse {
                print("HTTP Status code is \(httpResponse.statusCode)")
            }

            self.webView.loadData(data!, MIMEType: mimeType, textEncodingName: encoding, baseURL: url)
        }
    }
    task.resume()
}

你这样称呼这个方法:

loadURL(NSURL(string: "https://apple.com")!)

在你之前这样做的地方:

webView.loadRequest(NSURLRequest(URL: NSURL(string: "https://apple.com")!))

【讨论】:

  • 感谢您的回答,我现在就试试。我现在得到的只是这两个标题。 Cache-Control: public, max-age=3600Expires: Thu, 25 Aug 2016 08:44:31 GMT我们应该从服务器添加其他东西吗?
  • 嗬,在这种情况下我们应该使用dataTaskWithRequest 而不是dataTaskWithURL。我刚刚编辑了我的答案以满足您的需要。
  • 是的,它现在正在工作,谢谢。但是你能告诉我,当标头只返回 Cache-Control: public, max-age=3600 和 Expires: Thu, 25 Aug 2016 08:44:31 GMT 时,它应该工作吗?
  • 老实说,我真的不知道:/。如果你找到原因,我会很感兴趣的!
猜你喜欢
  • 1970-01-01
  • 2011-08-13
  • 2016-01-18
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多