2015-01-23 25 views
9

Ich bin neu in Xcode und Swift.Den Cache von UIWebView in Swift löschen

Ich habe ein UIWebView in meiner App. Dieses UIWebView muss jedes Mal vollständig neu geladen werden (d. H. Alle Zwischenspeicher von Bildern/HTML/Cookies usw. löschen), wenn viewDidLoad.

Also gibt es irgendeinen Code, den ich in Swift machen kann?

Hier ist mein Code:

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

Dank!

Antwort

20

können Sie verwenden

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 

Sie können auch die Cache-Politik der 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) 

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) 

Swift 3.0 ändern

Weitere Informationen zu den Cache-Regeln: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/index.html#//apple_ref/c/tdef/NSURLRequestCachePolicy

+0

Sorry, möchte ich, dass fragen, ob 'timeoutInterval' in Sekunden oder Minuten zu rechnen ist? – Arefly

+1

Sekunden. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/index.html#//apple_ref/occ/instp/NSURLRequest/timeoutInterval – rakeshbs

+0

http://shipster.com/ nsurlcache/sagt ReloadIgnoringLocalAndRemoteCacheData ist nicht implementiert. Das Radar stammt jedoch aus dem Jahr 2012 – wyu

9
NSURLCache.sharedURLCache().removeAllCachedResponses() 
if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies { 
    for cookie in cookies { 
     NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie) 
    } 
} 
5

Swift 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) 
    } 
}