作者:Love@YR
链接:http://blog.csdn.net/jingqiu880905/article/details/51075855
请尊重原创,谢谢!
做混合开发时发现UIWebView的内存问题很严重,尤其h5页面图片很多或者很大的时候就会出现内存警告。试了各种方法例如收到内存警告webView load一个空白页面,把delegate置为nil,或者限制缓存空间
int cacheSizeMemory = 1*1024*1024; // (内存缓存)
int cacheSizeDisk = 5*1024*1024; // (硬盘缓存在library/caches下面)
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
或者在收到内存警告后
NSURLCache * cache = [NSURLCache sharedURLCache]; [cache removeAllCachedResponses];
或者像这篇博客说的用老外的方法:http://blog.csdn.net/primer_programer/article/details/24855329
都没有用。
最后终于找到一篇文章感觉比较靠谱:http://zlm-90.blog.163.com/blog/static/136190688201472041157818/
stackoverflow上也有人说,UIWebView的memory缓存是禁不掉的。
后来发现说WKWebView(iOS 8和以上支持)比UIWebView占内存少了一半,速度提升一倍。于是试试转WKWebView。
UIWebView的delegate协议方法如下:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
分别对应着WKWebView的WKNavigationDelegate的协议方法:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
其中
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
方法里如果不允许load则调用 decisionHandler(WKNavigationActionPolicyCancel);
否则调用decisionHandler(WKNavigationActionPolicyAllow);
相当于之前UIWebView的shouldStartLoadWithRequest
里的return NO/YES
UIWebView的执行js方法为:
ret = [self.webView stringByEvaluatingJavaScriptFromString:js];
而WKWebView里需要替换此句为
[self.webView evaluateJavaScript:js completionHandler:^(id result, NSError *error) {
if (error == nil) {
if (result != nil) {
ret = [NSString stringWithFormat:@"%@", result];
}
} else {
NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
}
}];