1

I'm using a WKWebView to log into a Content Management System. After building the app, the WKWebView is still logged in to the website. How can I clear the cache that is storing this information?

Martin Muldoon
  • 3,010
  • 4
  • 20
  • 45

2 Answers2

0

I found this answer here.

if #available(iOS 9.0, *)
{
    let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
    let date = NSDate(timeIntervalSince1970: 0)

    WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler:{ })
}
else
{
    var libraryPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, false).first!
    libraryPath += "/Cookies"

    do {
        try FileManager.default.removeItem(atPath: libraryPath)
    } catch {
        print("error")
    }
    URLCache.shared.removeAllCachedResponses()
}
Community
  • 1
  • 1
f_qi
  • 499
  • 4
  • 20
0

I found the following code here: Removing cached data for WKWebView

let dataStore = WKWebsiteDataStore.default()
    dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { (records) in
        for record in records {
            print(record.displayName)
            if record.displayName.contains("facebook") {
                dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: [record], completionHandler: {
                    print("Deleted: " + record.displayName);
                })
            }
        }
Community
  • 1
  • 1
Martin Muldoon
  • 3,010
  • 4
  • 20
  • 45