2

I have an interesting problem: when my device is in Airplane Mode, the HTTP Status Code that the NSHHTPURLResponse provides is 200 "OK".

Shouldn't it fail with an error, or at least not respond that it has a valid connection with code 200?

Here is a snipit of my code:

let url = NSURL(string: "http://apple.com");

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    if(error == nil){
        let statusCode = (response as! NSHTTPURLResponse).statusCode;
        if(statusCode == 200){
            println("All Good");
        }
    }
}
task.resume();

In Airplane Mode, "All Good" is printed

Jake Chasan
  • 6,290
  • 9
  • 44
  • 90
  • 1
    Apple.com's `Cache-Control` headers indicate a `max-age` of `321`. So you're probably getting a cached result from the NSURLCache. – Aaron Brager Jun 13 '15 at 00:24

2 Answers2

0

Don't test error, test the data returned. Error (NSError, ErrorType) is used to return errors from the callback (inout).

The code below works for me.

I edited it with idiomatic Swift syntax:

let urlPath = "https://www.google.com/"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(url!) { data, response, error in
    if data != nil {
        NSLog("%@", NSString(data: data!, encoding: NSUTF8StringEncoding)!) // EDIT
        let res = response as? NSHTTPURLResponse
        if res?.statusCode == 200 {
            NSLog("All Good")
        }
    }
}

task!.resume()
John Difool
  • 5,572
  • 5
  • 45
  • 80
  • 1
    Unfortunately, it appears as though the data passed (even on Airplane Mode) is not nil. Is there a way to clear the cache? – Jake Chasan Jun 13 '15 at 02:42
  • Added the line to print what you are getting. If you are getting the content of the HTML page then I suspect you are using the simulator. There is no way to simulate airplane mode in the simulator. The workaround is to turn off your network on the Mac. – John Difool Jun 13 '15 at 06:46
0

Seems you may be getting an cached response. Check this article out.

.reloadIgnoringLocalCacheData

should solve your issue if this is the cause.

cachepolicy

Durdu
  • 4,649
  • 2
  • 27
  • 47