Search code examples
iosswiftwebviewnsurlcache

UIWebView request.response = nil Issue


I'm encountering an issue from UIWebView in the webViewDidFinishLoad and I'm getting

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

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

    }
}

as nil so I can't check the status code while the body is shown. Please where would be the issue? Is there something I can do from the server side?

Edit: from other requests I can see the response.


Solution

  • So, I think that's because you are checking NSURLCache to get your request response. But sometimes, your page can be displayed, but not cached. Indeed, the server can respond something like this:

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

    It says: "You should absolutely not cache my response". As a good citizen, iOS don't :). So, we have to use a different way to get back the server response. I think the best solution is to use NSURLSession to make your request, download the content and forward it to your webview. When the request is made, you will be able to access the answer is the completion handler. Here is an example of what you can do:

    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()
    }
    

    And you call this method like that:

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

    At the place you were doing this before:

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