I am loading a webpage in WKWebview using a cache policy NSURLRequestReturnCacheDataElseLoad. I don't need to clear the cache unless the server explicitly tells me to do this. But I ran into the problem of clearing the cache as soon as the server tells me to do this.
Most of the answers and articles show what removeAllCachedResponsesworks, although there are a few complaints circulating around about NSURLCache not working properly with NSURLSession or UIWebView. I could not get it to work for me in either iOS 8.4 or 9.3 simulators.
So, I used the following code to clear all files in the cache directory. The cached website files that I use in my WKWebview are located in Application / Cache / bundleidentifier. Although, I am trying to delete all the files that I can. When I run the code, I get an error message that tries to delete / Snapshots. Now it made me wonder what other files in the cache directory should I intervene? I know that the SDWebImage cache and several other files are in this directory. But I still need to clear the SDWebImage cache.
Here is the code I used to clear the cache directory:
public func clearCache(){
let cacheURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first!
let fileManager = NSFileManager.defaultManager()
do {
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'm missing to achieve the same?