【问题标题】:iOS Swift - URLSessionDataTask doesn't get updated JSON data on refreshiOS Swift - URLSessionDataTask 在刷新时没有得到更新的 JSON 数据
【发布时间】:2019-07-31 07:58:14
【问题描述】:

我有一个简单的应用程序,我通过这种方式从存储在我自己的服务器中的 JSON 文件中获取数据 - 我正在使用 SwiftyJSON

func queryData(_ fileName:String) {
        guard let url = URL(string: JSON_PATH + fileName + ".json") else {return} // JSON_PATH + fileName + ".json" is the complete path to my db.json file (see below)
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let dataResponse = data, error == nil else {
                self.simpleAlert(error!.localizedDescription)
                return
            }
            let jsonData = try! JSON(data: dataResponse)
            print("ARRAY: \(jsonData)")
        }
        task.resume()
    }



这是我的db.json 文件:

[
    {
        "objID":"GNoW3vszYz",
        "string":"First (1) string",
        "pointer":["pointer","yN76TF43i8"],
        "boolean":true,
        "number":123,
        "fileURL":"https://example.com/uploads/01.jpg",
        "array":["aaa","bbb","ccc"]
    },
    {
        "objID":"yN76TF43lD",
        "string":"Second (2) string",
        "pointer":["pointer","GNoN3vsz2I"],
        "boolean":false,
        "number":12.55,
        "fileURL":"https://example.com/uploads/02.jpg",
        "array":["aaa","eee","fff"]
    }
]



问题是,如果我手动编辑我的 db.json 文件,假设我将 "number":123, 更改为 "number":5555, 保存并再次将其上传到我的服务器并再次运行我的应用程序,控制台日志会显示相同的 JSON数据如上,就像我什么都没改变一样。


我已尝试杀死该应用程序并使用 Xcode 再次运行 2-3 次,但没有成功,我可以获得更新的 JSON 文件数据的唯一方法是删除该应用程序并通过 Xcode 重新安装.

有没有办法始终使用URLSessionDataTask 获取更新的 JSON 数据?
谢谢。

【问题讨论】:

  • 如果您的服务器启用了“Cache-Control”,URLSession 将缓存数据。创建 URLSessionConfiguration 并将其 requestCachePolicy 设置为 reloadIgnoringLocalCacheData。检查此打印响应并检查“Cache-Control”的值

标签: ios json swift database nsurlsessiondatatask


【解决方案1】:

这是由于URLSession缓存了来自服务器的数据,这通常是在来自服务器的json文件的header中发送的。

如果您无法在服务器端更改任何内容,那么您可以使用苹果文档中的.ephemeral here

使用此代码

let configuration = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: configuration)

.ephemeral 用于只存储在 ram 中的数据,不会存储在磁盘上的数据

【讨论】:

  • 谢谢,这就像一个魅力,而且很简单!
【解决方案2】:

我可以想到两种方法。

1) 在您的网址末尾添加当前日期时间

2) 禁用本地缓存。

对于 1)

extension Date {
    func currentTimeMillis() -> Int64 {
        return Int64(self.timeIntervalSince1970 * 1000)
    }
}

let url = URL(string: JSON_PATH + fileName + ".json?q=\(Date().currentTimeMillis())")

对于 2)

let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil

let session = URLSession.init(configuration: config)

取自SO

【讨论】:

  • 感谢您的回答,不过我宁愿使用 .ephemeral。
  • @xscoder np .ephemeral 是正确的方法。我不知道那个选项。
【解决方案3】:

这种行为也可能发生在存储在 Web 服务器上的文本文件(和其他非 JSON 文件)以及使用 URLSession 从该文本文件中获取数据的情况下。 .ephemeral 也适用于这种情况。

if let url = URL(string: "http://www.somerandomsite.com/mydata.txt") {
     let configuration = URLSessionConfiguration.ephemeral
     var urlSession = URLSession(configuration: configuration).dataTask(with: url) {(data, response, error) in
           if let error = error {
                print(error)
           }
      if var textFile = String(data: data!, encoding: .utf8){
           print(textFile)
      }
}
urlSession.resume()

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多