【问题标题】:URLSession datatask accessing older version of website?URLSession 数据任务访问旧版本的网站?
【发布时间】:2018-08-27 01:22:35
【问题描述】:

我正在使用 URLSession 从我的网站上抓取 JSON 数据。我的代码抛出了与转换类型相关的各种错误,所以我在代码中添加了一些打印语句,发现这个函数出于某种原因访问了我的网站的旧版本。此后,我更新了网站的数据,并通过自己访问网站和使用 Rested 验证了新数据是否正确显示。但是,下面代码中的打印语句会产生旧数据。该代码不会从磁盘读取数据,所以我不确定为什么会这样。

出于隐私目的,我已从我的代码中删除了该网站的链接,但可以在下面找到该功能。

   func websiteToDisk() {

        let config = URLSessionConfiguration.default

        config.waitsForConnectivity = true

        let defaultSession = URLSession(configuration: config)

        let url = URL(string: someURL)

        let task = defaultSession.dataTask(with: url!) { data, response, error in

            do {

                print("Getting information from website")

                if let error = error {

                    print(error.localizedDescription)

                } else if let data = data,

                    let response = response as? HTTPURLResponse,

                    response.statusCode == 200 {

                    //do {

                    let jsonDecoder = JSONDecoder()

                    print("about to dcode")

                    let decodedData = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]//try jsonDecoder.decode([String: [String]].self, from: data)

                    print(decodedData)

                    print("accessing dictionary")

                    print(decodedData!["busLoops"])

                    let toWrite = decodedData!["busLoops"] as! [String]



                    let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

                    let busLoopsURL = documentDirectoryURL.appendingPathComponent("busLoops").appendingPathExtension("json")



                    let jsonEncoder = JSONEncoder()

                    let jsonData = try jsonEncoder.encode(toWrite)

                    try jsonData.write(to: busLoopsURL)

                    //} catch { print(error)}

                }

            }

            catch { print(error)}

        }

        task.resume()

    }

【问题讨论】:

  • 那么你的问题是什么?
  • 如何推断
  • “如何推断”?这意味着什么?推断什么,从什么?具体点,伙计!

标签: ios swift nsurlsession


【解决方案1】:

尝试忽略本地缓存数据

guard let url = URL(string: "http://....") else{
    return
}
let request = NSMutableURLRequest(url: url)
request.cachePolicy = .reloadIgnoringCacheData
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, resp, error) in

}
task.resume()

【讨论】:

  • 有效!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 2011-10-04
  • 2019-10-13
  • 1970-01-01
  • 2011-11-18
  • 2021-09-01
  • 2015-10-12
相关资源
最近更新 更多