Search code examples
swiftuiwebview

Clearing UIWebView's Cache in Swift


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.

So is there any code I can do this in Swift?

Here is my code:

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

Thanks!


Solution

  • You can use

    NSURLCache.sharedURLCache().removeAllCachedResponses()
    NSURLCache.sharedURLCache().diskCapacity = 0
    NSURLCache.sharedURLCache().memoryCapacity = 0
    

    Swift 3.0

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

    You can also change the cache policy of the 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)
    

    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)
    

    For more information on cache policies : https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/index.html#//apple_ref/c/tdef/NSURLRequestCachePolicy