无法禁用请求缓存

时间:2017-01-28 17:45:16

标签: json caching swift3 urlrequest

我在SWIFT 3中遇到问题,尝试为请求禁用缓存,服务器发送更新的JSON文本,但我的应用程序仍显示旧数据。只有当蜂窝数据打开时才会发生这种情况,WIFI一切正常。 请告知如何解决这个问题,这是我的代码。谢谢!

    let tim: String = String(Date().timeIntervalSinceReferenceDate)
    let urlTim = url + "?timref=" + tim


    URLCache.shared.removeAllCachedResponses()
    URLCache.shared.diskCapacity = 0
    URLCache.shared.memoryCapacity = 0
    if let cookies = HTTPCookieStorage.shared.cookies {
        for cookie in cookies {
            HTTPCookieStorage.shared.deleteCookie(cookie)
        }
    }

    var request = URLRequest(url: URL(string: urlTim)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)

    request.httpMethod = "POST"
    request.httpBody = post.data(using: .utf8)
    request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData

    let task = URLSession.shared.dataTask(with: request)
    {
        data, response, error in guard let data = data, error == nil else { print("Network Error"); err?(); return; }
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("Network 200 error"); err?(); return; }
        self.jsonResponse = String(data: data, encoding: .utf8)!;
    }
    task.resume()

1 个答案:

答案 0 :(得分:0)

所以这是我的解决方案:

如果有人遇到这种情况并忘记添加cachepolicy选项,则必须手动清理缓存。代码生效后。

相关问题