2016-08-17 47 views
3

我使用NSURLRequestReturnCacheDataElseLoad缓存策略将网页加载到WKWebview。除非 服务器明确告诉我这样做,否则不需要我清除缓存。但是,一旦服务器告诉我要执行此操作,我将无法清除缓存它。在iOS中清除缓存目录的最佳做法是什么?

大多数的答案和文章表明,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) 
    } 
} 

现在,这是一个好的做法呢?是否有任何明显的方法,我失踪实现相同?

回答

2

清除缓存目录完全没问题。是的,迭代内容是它完成的方式。

这里是苹果说:

使用此目录编写任何特定的应用程序支持文件,你的 应用程序可以很容易地重新创建。您的应用通常负责管理此目录的内容,并根据需要添加和删除 文件。

File System Overview

2

你的代码是巨大的。我试图在WKWebsiteDataStore中使用removeDataOfTypes,但它不起作用。

这是夫特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) 
    } 
} 
相关问题