I load a webpage to WKWebview using NSURLRequestReturnCacheDataElseLoad
cache policy.There is no need for me to clear the cache unless the
server explicitly tells me to do it. But I am facing trouble clearing the cache, once the server tells me to do it.
Most of the answers and articles suggest that removeAllCachedResponses
works, though there are several complaints circulating around
about NSURLCache not working properly with NSURLSession or UIWebView.I couldn't get it to work for me either in iOS 8.4 or 9.3 simulators.
So I used the following code to clear all the files in the cache directory Programmatically. The cached files of the website that I use in my WKWebview reside in Application/Cache/bundleidentifier. Though, I try and delete all the files I can. When I run the code, I get an error trying to delete /Snapshots .Now this made me wonder what are some other files in the cache directory that I should not tamper with? I know the SDWebImage cache and few other files reside in this directory. But, I need to clear the SDWebImage cache anyways.
Here is the code I used to clear cache directory :
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)
}
}
Now, is this a good practice ? Are there any obvious methods that I am missing to achieve the same?
Your code is great. I tried to use removeDataOfTypes in WKWebsiteDataStore but it didn't work.
This is @Ashildr solution in Swift 3:
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With