gpt4 book ai didi

ios - 我在哪里为 Swift 2 中的 NSURLSession 指定 ReloadIgnoringLocalCacheData

转载 作者:行者123 更新时间:2023-11-30 13:43:32 25 4
gpt4 key购买 nike

我有一个应用程序,使用 NSURLSession 和 p2-oauth2 每 5 秒进行一次 API 调用。我遇到了一个问题,它返回缓存的数据而不是来自 API 的更新信息。我读过this post作者:Matt Thompson,他描述了不同的缓存策略,我认为我需要使用的是 ReloadIgnoringLocalCacheData。我认为它应该放在 AppDelegate DidFinishLaunchingWithOptions 函数中。但是,我遇到的问题是我不知道在哪里或如何指定它。我还没有找到任何 Swift 解决方案。谁能告诉我我的函数应该说什么?

如果有帮助,这是我的 API 请求:

    let urlPath = "https://sandbox-api.uber.com/v1/requests/\(uberRequestId)"
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

guard let endpoint = NSURL(string: urlPath) else { print("Error creating endpoint");return }
let request = appDelegate.oauth.request(forURL: NSURL(string:urlPath)!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "GET"

//get response from Uber and iterate through to find Uber Product ID.
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
do {
guard let dat = data else { throw JSONError.NoData }

let result = try NSJSONSerialization.JSONObjectWithData(dat, options: NSJSONReadingOptions.MutableContainers)

print(result)

//set status
status = result["status"] as! String

print("found status...returning it back -> \(status)")
completion(status: "\(status)")

} catch let error as JSONError {
print(error.rawValue)
print("ERROR NEEDS TO BE HANDLED.")
} catch {
print(error)
print("ERROR NEEDS TO BE HANDLED.")
}
}.resume()

最佳答案

这是正确设置缓存策略的最终请求。我添加了一行 ReloadIgnoringLocalCacheData

let urlPath = "https://sandbox-api.uber.com/v1/requests/\(uberRequestId)"
let url:NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let request = appDelegate.oauth.request(forURL: NSURL(string:urlPath)!)
request.HTTPMethod = "GET"

//added this line to set cache policy
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in

guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}

let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)

}

task.resume()

关于ios - 我在哪里为 Swift 2 中的 NSURLSession 指定 ReloadIgnoringLocalCacheData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35272712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com