最近发现app在打开一款H5游戏玩的时候经常莫名其妙就崩溃了,然后各种找原因发现在玩的时候memory消耗达将近200M,蒙了。这么大,而且退出后内存消耗也没怎么降下来。debug模式下玩了几次游戏崩溃,报错确实是内存问题。网上一查发现不是个例,基本来说是UIWebView本身的问题,大家都建议使用WKWebView。由于WKWebView是IOS8才开始的,所以在使用的时候我先判断IOS版本号,IOS8以上用WKWebview.经测试发现内存消耗大大减少,在打开同样的H5游戏的时候内存消耗降到了60M左右,加载速度似乎也快了很多,退出的时候内存消耗有释放掉,不会因为不断打开而持续升高。
具体使用方法:1.引入WebKit.framework.
2.在要用到的地方加入头文件 #import <WebKit/WebKit.h>
3.然后就是常规的用法了,要说的是弹窗问题,记得设置WKUIDelegate的2个方法,不然网页的alert弹不出来
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)())completionHandler
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
message:nil
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action) {
completionHandler();
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
message:nil
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
completionHandler(YES);
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action){
completionHandler(NO);
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}