Ash*_*ldr 6 objective-c ios swift
我使用NSURLRequestReturnCacheDataElseLoad缓存策略将网页加载到WKWebview .除非服务器明确告诉我这样做,否则我无需清除缓存.但是,一旦服务器告诉我这样做,我就无法清除缓存.
大多数答案和文章都表明这是removeAllCachedResponses 有效的,尽管有一些关于NSURLCache的投诉在NSURLSession或UIWebView上无法正常工作.我无法在iOS 8.4或9.3模拟器中使用它.
所以我使用以下代码以编程方式清除缓存目录中的所有文件.我在WKWebview中使用的网站缓存文件位于Application/Cache/bundleidentifier中.虽然,我尝试删除所有文件.当我运行代码时,我收到错误尝试删除/快照.现在这让我想知道缓存目录中的其他文件是什么,我不应该篡改?我知道SDWebImage缓存和其他一些文件驻留在这个目录中.但是,我还是需要清除SDWebImage缓存.
这是我用来清除缓存目录的代码:
public func clearCache(){
let cacheURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first!
let fileManager = NSFileManager.defaultManager()
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL( cacheURL, includingPropertiesForKeys: nil, options: [])
for file in directoryContents {
do {
try fileManager.removeItemAtURL(file)
}
catch let error as NSError {
debugPrint("Ooops! Something went wrong: \(error)")
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
Run Code Online (Sandbox Code Playgroud)
现在,这是一个好习惯吗?是否有任何明显的方法可以实现相同的方法?
你的代码很棒.我试图在WKWebsiteDataStore中使用removeDataOfTypes但它不起作用.
这是Swift 3中的@Ashildr解决方案:
func clearCache(){
let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
let fileManager = FileManager.default
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory( at: cacheURL, includingPropertiesForKeys: nil, options: [])
for file in directoryContents {
do {
try fileManager.removeItem(at: file)
}
catch let error as NSError {
debugPrint("Ooops! Something went wrong: \(error)")
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3035 次 |
| 最近记录: |