2015-01-23 27 views
9

Tôi mới sử dụng Xcode và Swift.Xóa bộ nhớ cache của UIWebView trong Swift

Tôi có UIWebView bên trong ứng dụng của mình. UIWebView này cần phải được tải lại đầy đủ (nghĩa là xóa tất cả bộ nhớ cache của hình ảnh/HTML/cookie, v.v.) mỗi lần khi viewDidLoad.

Vì vậy, có bất kỳ mã nào tôi có thể thực hiện việc này trong Swift không?

Đây là mã của tôi:

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

Cảm ơn!

Trả lời

20

Bạn có thể sử dụng

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 

Bạn cũng có thể thay đổi chính sách bộ nhớ cache của 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) 

Để biết thêm thông tin về chính sách cache: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/index.html#//apple_ref/c/tdef/NSURLRequestCachePolicy

+0

Xin lỗi, tôi muốn hỏi rằng nếu 'timeoutInterval' được đếm trong vài giây hoặc vài phút? – Arefly

+1

giây. 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/nói ReloadIgnoringLocalAndRemoteCacheData không được triển khai. Radar là từ năm 2012 mặc dù – 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) 
    } 
} 
Các vấn đề liên quan