首页 > 解决方案 > 如何在 Swift 中禁用缓存

问题描述

在我的 iOS 应用程序中,我发现当我直接从浏览器调用 url 时,我会得到一个最新的 json,而当从应用程序内调用它时,我会得到一个旧版本的 json。我已经在加载 URL 的代码片段下面发布了。

func getItems() {
    //Hit the web service Url
    let serviceUrl = "omitted"

    //Download the json data
    let url = URL(string: serviceUrl)
    if let url = url{
        //Create a URL Session
        let session = URLSession(configuration: .default)
        let task = session.dataTask(with: url, completionHandler: {(data, response, error) in
            if error == nil {
                //Succeeded
                //Call the parse json function on the data
                self.parseJson(data!)
            }
            else {
                print("error occured in getItems")
            }
        })
        // Start the task
        task.resume()
    }
}

标签: jsonswiftweb-scraping

解决方案


您可以cachePolicyURLRequest中设置

您的代码将是

func getItems() {
        //Hit the web service Url
        let serviceUrl = "omitted"
        let url = URL(string: serviceUrl)
        //Download the json data
        if let url = url{
            //Create a URL Session
            let session = URLSession(configuration: .default)
            let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 15.0)
            let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
                if error == nil {
                    //Succeeded
                    //Call the parse json function on the data
                    self.parseJson(data!)
                }
                else {
                    print("error occured in getItems")
                }
            })
            // Start the task
            task.resume()
        }
    }

推荐阅读