NSHTTPURLResponse Status Code 200 in Airplane Mode

1.9k views Asked by At

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

2

There are 2 answers

2
John Difool On

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()
0
Durdu On

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

.reloadIgnoringLocalCacheData

should solve your issue if this is the cause.

cachepolicy