Clearing UIWebView's Cache in Swift

后端 未结 5 1586
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 03:45

I have a UIWebView inside my app. This UIWebView needs to be reloaded fully (i.e. clear all cache of images/HTML/cookies etc.) every time when viewDidLoad.

5条回答
  •  我在风中等你
    2020-12-30 04:02

    Swift 4

    func clear(cache: Bool, cookies: Bool) {
        if cache { clearCache() }
        if cookies { clearCookies() }
    }
    
    fileprivate func clearCache() {
        URLCache.shared.removeAllCachedResponses()
        URLCache.shared.diskCapacity = 0
        URLCache.shared.memoryCapacity = 0
    }
    
    fileprivate func clearCookies() {
        let cookieStorage = HTTPCookieStorage.shared
    
        guard let cookies = cookieStorage.cookies else { return }
    
        for cookie in cookies {
            cookieStorage.deleteCookie(cookie)
        }
    }
    

    If the desired outcome is to have a private browsing experience, you may also want to set the websiteDataStore property on your WKWebViewConfiguration object per the below.

        let configuration = WKWebViewConfiguration()
        configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
        ...
    

提交回复
热议问题