在Swift中清除UIWebView的缓存

He *_*何一非 13 uiwebview swift

我的应用程序中有一个UIWebView.每次都需要完全重新加载此UIWebView(即清除所有图像/ HTML/cookie缓存等)viewDidLoad.

那么在Swift中我可以做任何代码吗?

这是我的代码:

let myUrl = NSURL(string: "http://www.example.com")
let myRequest = NSURLRequest(URL: myUrl!)
myWebView.loadRequest(myRequest)
Run Code Online (Sandbox Code Playgroud)

谢谢!

rak*_*hbs 28

您可以使用

NSURLCache.sharedURLCache().removeAllCachedResponses()
NSURLCache.sharedURLCache().diskCapacity = 0
NSURLCache.sharedURLCache().memoryCapacity = 0
Run Code Online (Sandbox Code Playgroud)

Swift 3.0

URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
Run Code Online (Sandbox Code Playgroud)

您还可以更改的缓存策略 NSURLRequest

let day_url = NSURL(string: "http://www.domain.com")
let day_url_request = NSURLRequest(URL: day_url,
    cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,
    timeoutInterval: 10.0)

let day_webView = UIWebView()
day_webView.loadRequest(day_url_request)
Run Code Online (Sandbox Code Playgroud)

Swift 3.0

let day_url = URL(string: "http://www.domain.com")
let day_url_request = URLRequest(url: day_url!,
    cachePolicy:NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData,
    timeoutInterval: 10.0)

let day_webView = UIWebView()
day_webView.loadRequest(day_url_request)
Run Code Online (Sandbox Code Playgroud)

有关缓存策略的更多信息:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/index.html#//apple_ref/c/tdef/NSURLRequestCachePolicy


Ash*_*hok 10

final class WebCacheCleaner {

    class func clear() {
        URLCache.shared.removeAllCachedResponses()

        HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)
        print("[WebCacheCleaner] All cookies deleted")

        WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
            records.forEach { record in
                WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
                print("[WebCacheCleaner] Record \(record) deleted")
            }
        }
    }

}

// Usage
WebCacheCleaner.clear()
Run Code Online (Sandbox Code Playgroud)


Cod*_*ide 10

斯威夫特3.

URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0

if let cookies = HTTPCookieStorage.shared.cookies { 
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}
Run Code Online (Sandbox Code Playgroud)