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

时间:2016-02-08 15:02:38

标签: ios swift oauth-2.0 nsurlsession

我有一个应用程序,使用NSURLSession和p2-oauth2每5秒进行一次API调用。我遇到了一个问题,即返回缓存数据而不是来自API的更新信息。我阅读了Matt Thompson撰写的this post,其中描述了不同的缓存策略,我认为我需要使用的是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()

2 个答案:

答案 0 :(得分:0)

假设OAuth API返回可变请求,您可以将其 cachePolicy 属性设置为NSURLRequestCachePolicy.ReloadIgnoringCacheData。

答案 1 :(得分:0)

以下是正确设置缓存策略的最终请求。我在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()