2015-01-23 13 views
9

Sono nuovo di Xcode e Swift.Cancellazione della cache di UIWebView in Swift

Ho un UIWebView all'interno della mia app. Questa UIWebView deve essere ricaricata completamente (cioè svuota tutte le cache di immagini/HTML/cookie ecc.) Ogni volta che si utilizza viewDidLoad.

Quindi c'è qualche codice che posso fare in Swift?

Ecco il mio codice:

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

Grazie!

risposta

20

È possibile utilizzare

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 

si può anche cambiare la politica della cache del 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) 

Per ulteriori informazioni sulle politiche di cache: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/index.html#//apple_ref/c/tdef/NSURLRequestCachePolicy

+0

dispiace, voglio chiedere che se 'timeoutInterval' si conta in secondi o minuti? – Arefly

+1

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

+0

http://nshipster.com/ nsurlcache/dice che ReloadIgnoringLocalAndRemoteCacheData non è implementato. Il radar è del 2012 però – 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) 
    } 
} 
Problemi correlati