web-dev-qa-db-fra.com

Comment supprimer le cache dans WKWebview?

Quelqu'un a travaillé avec WKWebview et a essayé d'effacer le cache? Si oui, comment faire? un exemple?

P.S. : Normal NSURLCache ne fonctionne pas. 

24
Sravan

Sous iOS 9

//// Optional data
NSSet *websiteDataTypes
= [NSSet setWithArray:@[
                        WKWebsiteDataTypeDiskCache,
                        //WKWebsiteDataTypeOfflineWebApplicationCache,
                        WKWebsiteDataTypeMemoryCache,
                        //WKWebsiteDataTypeLocalStorage,
                        //WKWebsiteDataTypeCookies,
                        //WKWebsiteDataTypeSessionStorage,
                        //WKWebsiteDataTypeIndexedDBDatabases,
                        //WKWebsiteDataTypeWebSQLDatabases,
                        //WKWebsiteDataTypeFetchCache, //(iOS 11.3, *)
                        //WKWebsiteDataTypeServiceWorkerRegistrations, //(iOS 11.3, *)
                        ]];
//// All kinds of data
//NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
//// Date from
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//// Execute
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
   // Done
}];
47
Shingo Fukuyama

Version Swift:

if #available(iOS 9.0, *) {
  let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
  let date = NSDate(timeIntervalSince1970: 0)
  WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(websiteDataTypes as! Set<String>, modifiedSince: date, completionHandler:{ })
} else {
    var libraryPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, false).first!
    libraryPath += "/Cookies"

    do {
      try NSFileManager.defaultManager().removeItemAtPath(libraryPath)
    } catch {
      print("error")
    }
    NSURLCache.sharedURLCache().removeAllCachedResponses()
}

Version Swift3:

   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()
    }
32
Esqarrouth

Vous ne pouvez pas supprimer des caches uniquement avec NSURLCache . Après de nombreux essais, je pourrais vider les caches en procédant comme suit (à partir de iOS 8.1.1):

  1. Utilisez NSURLCache pour supprimer les caches de la même manière que vous le faisiez sur UIWebView. Si vous utilisez WKProccessPool, réinitialisez-le.
  2. Supprimer le répertoire Caches dans Library.
  3. Supprimer tous les WKWebViews

La prochaine fois que vous créerez WKWebView, les caches devraient être effacés.

ShingoFukuyama/WKWebViewTips

2
Shingo Fukuyama

J'ai pu résoudre ce problème en ayant mon WKWebView évaluer window.location.reload. J'ai un outil de reconnaissance des gestes pour la frappe sur la vue Web et chaque fois qu'il détecte une double frappe avec 2 touches, je lance ce qui suit:

webView.evaluateJavaScript("window.location.reload(true)", completionHandler: nil);

J'espère que cela t'aides.

2
harrisonlee

Quelque chose de similaire pour iOS 9.0 et versions ultérieures:

let store: WKWebsiteDataStore = WKWebsiteDataStore.default()
let dataTypes: Set<String> = WKWebsiteDataStore.allWebsiteDataTypes()
store.fetchDataRecords(ofTypes: dataTypes, completionHandler: { (records: [WKWebsiteDataRecord]) in
  store.removeData(ofTypes: dataTypes, for: records, completionHandler: {
    // do your thing here
  })
})
1
nouatzi

Travaillé
Swift 3. Version.
Pour l'ancienne version Swift

import Foundation
import WebKit

func removeWebData() {

    if #available(iOS 9.0, *) {

        let websiteDataTypes = WKWebsiteDataStore.allWebsiteDataTypes()
        let date = NSDate(timeIntervalSince1970: 0)

        WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: date as Date, completionHandler: {
            #if DEBUG

                print("remove all data in iOS9 later")

            #endif
        })

    }else {

        // Remove the basic cache.
        URLCache.shared.removeAllCachedResponses()

        // Delete system cookie store in the app
        let storage = HTTPCookieStorage.shared
        if let cookies = storage.cookies {
            for cookie in cookies {
                storage.deleteCookie(cookie)
            }
        }


        do {
            // folder 를 삭제하는 대신 contents 를 삭제하는 이유?
            // MainVC 가 호출되면 cache, cookie가 발생하므로 로딩시 확인된 cache, cookie 폴더의
            // contents 에 대해서만 삭제 진행.

            // Clear web cache
            try deleteLibraryFolderContents(folder: "Caches")

            // Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
            try deleteLibraryFolderContents(folder: "Cookies")

            // Removes all app cache storage.
            try deleteLibraryFolder(folder: "WebKit")

        } catch {
            #if DEBUG

                print("Delete library folders error in iOS9 below")

            #endif

        }
    }
}

/**
 Delete folder in library

 - parameter folder: a folder you want to delete

 - throws: throws an error
 */
func deleteLibraryFolder(folder: String) throws {
    let manager = FileManager.default
    let library = manager.urls(for: .libraryDirectory, in: .userDomainMask).first!
    let dir = library.appendingPathComponent(folder)
    try manager.removeItem(at: dir)
}

/**
 Delete contents in library folder

 - parameter folder: target folder

 - throws: throws an error
 */
private func deleteLibraryFolderContents(folder: String) throws {
    let manager = FileManager.default
    let library = manager.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask)[0]
    let dir = library.appendingPathComponent(folder)
    let contents = try manager.contentsOfDirectory(atPath: dir.path)
    for content in contents {
        do {
            try manager.removeItem(at: dir.appendingPathComponent(content))
        } catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) {
            // "EPERM: operation is not permitted". We ignore this.
            #if DEBUG

                print("Couldn't delete some library contents.")

            #endif
        }
    }
}
1
ZAFAR007

Swift 3.x version du post de @ Esqarrouth

func clearCache() {
    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()
    }
}
0
zingle-dingle

Cela me prend quelques heures, mais cela fonctionne pour moi! Après le loadRequest, je fais un reloadFromOrigin! Alors je force le cache vide! [WKWebView loadRequest: demande]; [WKWebView reloadFromOrigin];

0
Valentin Thomalla

Ça marche pour moi

 if #available(iOS 9.0, *) {
            let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
            let date = NSDate(timeIntervalSince1970: 0)
            WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(websiteDataTypes as! Set<String>, modifiedSince: date, completionHandler:{ })
        }
        else
        {
          NSURLCache.sharedURLCache().removeAllCachedResponses()
        }
0
Durai Amuthan.H