【问题标题】:NSHTTPURLResponse Status Code 200 in Airplane Mode飞行模式下的 NSHTTPURLResponse 状态码 200
【发布时间】:2023-04-07 01:13:01
【问题描述】:

我有一个有趣的问题:当我的设备处于飞行模式时,NSHHTPURLResponse 提供的 HTTP 状态代码是200“OK”。

它不应该因为错误而失败,或者至少不响应它与代码 200 的有效连接吗?

这是我的代码片段:

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

在飞行模式下,会打印“All Good”

【问题讨论】:

  • Apple.com 的 Cache-Control 标头表示 max-age321。所以你可能会从 NSURLCache 中得到一个缓存的结果。

标签: ios swift nsurlsession nserror nshttpurlresponse


【解决方案1】:

不测试错误,测试返回的数据。错误(NSError,ErrorType)用于从回调(inout)返回错误。

下面的代码对我有用。

我用惯用的 Swift 语法编辑了它:

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

【讨论】:

  • 不幸的是,似乎传递的数据(即使在飞行模式下)也不是零。有没有办法清除缓存?
  • 添加了打印你得到的东西的行。如果您正在获取 HTML 页面的内容,那么我怀疑您正在使用模拟器。没有办法在模拟器中模拟飞行模式。解决方法是关闭 Mac 上的网络。
【解决方案2】:

您似乎收到了缓存响应。检查this article

.reloadIgnoringLocalCacheData

如果这是原因,应该解决您的问题。

cachepolicy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2011-08-13
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多