2015年8月11日 星期二

[iOS] WebView loadHTMLString clear css cache every time

在iOS寫一個WebView
常常打開過的內容都會cache住
如果下一次打開時都還會是使用上一次的CSS設定

查找了資料通常都是使用

[[NSURLCache sharedURLCache] removeAllCachedResponses];
因為我是用

- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;

就算加了removeAllCachedResponses
還是要等到App從記憶體消失時才會重新載入CSS
於是參考了這篇的作法
每次loadHTMLString時直接更改css的版本
欺騙UIWebView讓它以為每次讀取的css都不一樣

NSString *contentString = [htmlString stringByReplacingOccurrencesOfString:@"style.css" withString:[NSString stringWithFormat:@"style.css?time=%@", [[NSDate date] description]]];
[self.webView loadHTMLString:contentString baseURL:nil];
refer:http://stackoverflow.com/questions/3549508/prevent-caching-of-css-files-in-uiwebview-loaded-from-disk

沒有留言:

張貼留言