我正在开发一个测验应用程序,该应用程序使用各种API调用从数据库中提取数据。出于某种原因,当我尝试提取新数据时(我们已经添加/删除了数据库中的测验),我得到了旧的JSON,直到我卸载并重新安装应用程序到模拟器上。我打印出检索到的JSON,手机正在显示相同的测验。奇怪的是,如果我们在浏览器中执行请求,我们会在编辑数据库后立即看到更新的JSON。更奇怪的是它工作正常(每当我们重新加载视图时更新)直到今天,我们的排行榜视图正在正常更新。在数据库上工作的那个人发誓说他还没有改变任何东西,但我还没有触及几周内处理API调用的功能。任何建议将不胜感激。我将使用下面的方法。
func getQuizTitles() {
let getQuizTitlesURL = URL(string: "(api_url_here)")
URLSession.shared.dataTask(with: getQuizTitlesURL! as URL, completionHandler: {(data, response, error) in
print(response as Any)
do{
if let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray {
print(parsedData)
var title:String
var creator:String
var length:Int
var quizId:Int
let questions:[Question] = []
for index in 0...parsedData.count-1 {
let aObject = parsedData[index] as! [String : AnyObject]
title = (aObject["Title"] as? String)!
if aObject["Creator"] as? String == nil {
creator = ""
}else{
creator = aObject["Creator"] as! String
}
//length = aObject["Length"]
length = 0
quizId = (Int((aObject["ID"] as? String)!)!)
let quiz:Quiz = Quiz(title: title, creator: creator, length: length, quizId: quizId , questions: questions)
self.quizArray.append(quiz)
}
}
if let HTTPResponse = response as? HTTPURLResponse {
print(HTTPResponse)
let statusCode = HTTPResponse.statusCode
if statusCode == 200 {
print("Success")
}
}
}catch let error as NSError {
print(error)
}
DispatchQueue.main.async {
self.tableViewOutlet.reloadData()
}
}).resume()
}
答案 0 :(得分:0)
显然,应用程序出于某种原因开始缓存数据。我添加了这两行并修复了它。
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
但是,如果您要发出请求,则可以在初始化请求后添加此行。
var request: URLRequest = URLRequest(url: getQuestionsFromIdURL!)
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData