为什么它缓存响应。它返回以前获取的响应。它甚至可以在关闭网络连接的情况下工作。重置 iOS 模拟器似乎也不起作用。发出请求,然后再次与互联网脱机确实有效(缓存)。
public let urlSession: NSURLSession
public init()
{
// ...
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.requestCachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
urlSession = NSURLSession(configuration: configuration)
}
func makeRequest(path: String, httpMethod:String, body:String?, baseUrl: String?, headers:[String:String]=[:], callback: JsonRequestCallback)
{
let urlString = (baseUrl ?? customOAuth2Manager.API_URL) + path
let url = NSURL(string: urlString)
let request = oauthInstance.request(forURL: url!)
request.HTTPMethod = httpMethod
self.customOAuth2Manager.setupRequest(request)
for (key, value) in headers {
request.setValue(value, forHTTPHeaderField:key)
}
if let body = body where body != "" {
let postData = (body as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = postData
}
let task = urlSession.dataTaskWithRequest(request) { data, response, error in
self.parseData(data, response:response, error:error, body:body, callback: callback)
}
task.resume()
}
更新
didFinishLaunching
我设法通过从以下位置调用此代码来解决它AppDelegate
:
func removeUrlCache()
{
NSURLCache.setSharedURLCache(NSURLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil))
}
但是,我仍然很好奇为什么我的原始代码不起作用。禁用所有应用程序的缓存以解决我的问题也感觉有点难看。