首页 > 解决方案 > 清除缓存的 URL

问题描述

我有一个下面的代码,除了拉刷新之外,它工作正常。它返回 .json 的缓存版本。如果我使用不同的 URL 函数,它会即时重新加载新的 .json,但如果我想使用相同的 URL 执行拉取刷新,它会提供缓存版本。

谢谢

static func loadDataFromURL(url: URL,completion: @escaping (_ data: Data?, _ error: Error?) -> Void) {

    let sessionConfig = URLSessionConfiguration.default
    sessionConfig.allowsCellularAccess = true
    sessionConfig.timeoutIntervalForRequest = 15
    sessionConfig.timeoutIntervalForResource = 30
    sessionConfig.httpMaximumConnectionsPerHost = 1

    let session = URLSession(configuration: sessionConfig)

    // Use URLSession to get data from an NSURL
    let loadDataTask = session.dataTask(with: url) { data, response, error in

        guard error == nil else {
            completion(nil, error!)
            if kDebugLog { print("API ERROR: \(error!)") }
            return
        }

        guard let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode else {
            completion(nil, nil)
            if kDebugLog { print("API: HTTP status code has unexpected value") }
            return
        }

        guard let data = data else {
            completion(nil, nil)
            if kDebugLog { print("API: No data received") }
            return
        }

        // Success, return data
        completion(data, nil)
    }

    loadDataTask.resume()
}

标签: jsonswifturlcaching

解决方案


您应该使用 URLSessionConfiguration 对象设置 session.configuration,该对象根据您的需要配置缓存策略,我认为您没有在上面的代码中设置。


推荐阅读