Очистка кэша UIWebView в Swift
У меня есть UIWebView внутри моего приложения. Этот UIWebView необходимо полностью перезагружать (т.е. очищать весь кэш изображений /HTML/файлов cookie и т.д.) Каждый раз, когда viewDidLoad
.
Так есть ли код, который я могу сделать в Swift?
Вот мой код:
let myUrl = NSURL(string: "http://www.example.com")
let myRequest = NSURLRequest(URL: myUrl!)
myWebView.loadRequest(myRequest)
Спасибо!
Ответы
Ответ 1
Вы можете использовать
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
Вы также можете изменить политику кэширования 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)
Дополнительные сведения о политиках кэша: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/index.html#//apple_ref/c/tdef/NSURLRequestCachePolicy
Ответ 2
Swift 4:
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()
Старые версии:
NSURLCache.sharedURLCache().removeAllCachedResponses()
if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies {
for cookie in cookies {
NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie)
}
}
Ответ 3
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)
}
}
Ответ 4
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)
}
}
Если желаемым результатом будет использование частного просмотра, вы также можете установить свойство websiteDataStore
для объекта WKWebViewConfiguration
в соответствии с приведенным ниже описанием.
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
...