Sun*_*kas 20 caching nsurlcache nsurlsession nsurlsessionconfiguration swift
为什么它会缓存响应.它返回先前获取的响应.它甚至可以在关闭网络连接时工作.重置iOS模拟器似乎也不起作用.提出请求,然后再次使用Internet脱机工作(缓存).
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()
}
Run Code Online (Sandbox Code Playgroud)
更新
我设法通过调用该代码来解决它didFinishLaunching在AppDelegate:
func removeUrlCache()
{
NSURLCache.setSharedURLCache(NSURLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil))
}
Run Code Online (Sandbox Code Playgroud)
但是,我仍然很好奇为什么我的原始代码不起作用.为所有应用程序禁用缓存以解决我的问题也感觉有点难看.
Ger*_*ost 18
谢谢你的提问.它让我走上了正确的道路.
有更多的可能性,NSURLCache.sharedURLCache()您不需要为此更改内存容量和磁盘容量.
您可以删除所有缓存的响应.适合我.
URLCache.shared.removeAllCachedResponses()
Run Code Online (Sandbox Code Playgroud)
或者,您可以删除单个响应的缓存.不适用于iOS 9.
let request = URLRequest(url: URL(string: url)!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
URLCache.shared.removeCachedResponse(for: request)
//Do your request here
Run Code Online (Sandbox Code Playgroud)
我希望它可以帮助别人!
编辑:
NSURLCache.sharedURLCache().removeCachedResponseForRequest(request)不幸的是不适合我
我的替代方案是:我正在使用它来进行刷新,我正在跟踪上次更新日期.所以我使用以下代码:
URLCache.shared.removeCachedResponses(since: lateUpdate)
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,这不是以太工作.
从iOS 8开始,单缓存删除方法似乎被打破:https://stackoverflow.com/a/26343653/2826164
And*_*rej 11
不确定这是否真的会阻止chaching或者每次都强制重新加载,但这对我有用:
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
Run Code Online (Sandbox Code Playgroud)
这是一个截图,显示其他选项,以防有人可能需要它们: