json - 如何在 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()
}
}
解决方案
您可以cachePolicy
在URLRequest中设置
您的代码将是
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()
}
}
推荐阅读
- javascript - 如何在基于一个下拉列表(即部门)的输出和一个 jquery 表的总值的 Html 中创建一个依赖下拉列表
- c++ - C ++中的上下文选择类似功能
- visual-studio-code - VSCODE 总是使用 Edge 打开 ctrl_click 链接(如 launch.json 评论),我想使用 Chrome
- python - Pandas 数据框找不到列名 KeyError
- latex - 使用 esttab 导出具有 2 个组分类的 LaTeX 回归表
- python - Jenkinsfile 并允许一个中止的 bat() 命令时间来清理
- swift - 如何在 ARKit 中使用我自己的遮挡 ML 模型?
- xamarin.mac - 如何在 .NET 6 中创建引用 Xamarin.Mac.dll 的控制台应用程序
- c# - 不能蹲下为我的平台游戏工作
- l-systems - 如何从图像构建 l 系统