WKWebView
iOS8以后,苹果新增加了WebKit框架了,提供了WKWebView这个全新的浏览器控件。对比UIWebView,最直观的感受就是程序占用内存大幅度降低了,加载速度快了,内存泄漏问题也解决了。
WKWebView使用技巧
WKWebView缓存相关
如果想及时的清理WKWebView产生的缓存,可以使用以下方法:
iOS9及之后的:
NSSet *websiteDataTypes
= [NSSet setWithArray:@[
WKWebsiteDataTypeDiskCache,
WKWebsiteDataTypeMemoryCache,
]];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//// Execute
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
// Done
}];
iOS8:
NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:@"/Cookies"];
[[NSFileManager defaultManager] removeItemAtPath:cachePath error:nil];
自定义WKWebView的User-Agent:
NSString *newAgent = [oldAgent stringByAppendingString:@"***"];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : newAgent}];
或者
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:@"***" forHTTPHeaderField:@"User-Agent"];
[self.webView loadRequest:request];
WKWebView与JS的交互
如果是简单的接受JS的通知信息,可以实现WKUIDelegate的其中一些方法:
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
当JS调用alert、panel、prompt方法时,如果实现了以上的方法则调用以上方法。
如果是自定义可供JS调用方法的对象,则应该在WKWebView初始化过程中注入实现了WKScriptMessageHandler协议的交互对象:
WKUserContentController *userContentController = [WKUserContentController new];
[userContentController addScriptMessageHandler:[MyJSHandler new] name:@"MyJSHandler"];
// Create the configuration with the user content controller
WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
configuration.userContentController = userContentController;
_shareWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
JS方调用交互对象方法如下:
var messsage="test";
if(window.MyJSHandler) {
window.MyJSHandler.postMessage(message);
} else {
window.webkit.messageHandler.MyJSHandler.postMessage(message);
}
动态获取WKWebView可滚动区域的大小
对WKWebView的scrollSize进行KVO就可以动态获取其滚动区域大小
[_shareWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (object == _shareWebView.scrollView && [keyPath isEqual:@"contentSize"]) {
UIScrollView *scrollView = _shareWebView.scrollView;
CGRect rect = _shareWebView.frame;
JZLog(@"web view height : %f",scrollView.contentSize.height);
}
}
禁止WKWebView的长按呼出菜单
在WKWebView的初始化过程中注入JS代码
NSString *source = @"var style = document.createElement('style'); \
style.type = 'text/css'; \
style.innerText = '*:not(input):not(textarea) { -webkit-user-select: none; -webkit-touch-callout: none; }'; \
var head = document.getElementsByTagName('head')[0];\
head.appendChild(style);";
WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
// Create the user content controller and add the script to it
WKUserContentController *userContentController = [WKUserContentController new];
[userContentController addUserScript:script];
// Create the configuration with the user content controller
WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
configuration.userContentController = userContentController;
_shareWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
禁止WKWebView的捏合手势放大缩小
实现WKNavigationDelegate中的以下方法并执行JS代码
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
// 禁止放大缩小
NSString *injectionJSString = @"var script = document.createElement('meta');"
"script.name = 'viewport';"
"script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
[webView evaluateJavaScript:injectionJSString completionHandler:nil];
}
WKWebView使用过程中要注意的坑点
Cookie相关
WKWebView 的存储体系与 UIWebVIew 完全不一样,只能手动给它添加 Cookie。
//自己设定请求的Cookie值
[request setValue:myCookie forHTTPHeaderField:@"Cookies"];
//或者在WKWebView初始化时候注入JS代码
NSString *source = [NSString stringWithFormat:@"ocument.cookies=%@",myCookie];
WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
// Create the user content controller and add the script to it
WKUserContentController *userContentController = [WKUserContentController new];
[userContentController addUserScript:script];
// Create the configuration with the user content controller
WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
configuration.userContentController = userContentController;
_shareWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
WKWekView的请求不会被NSURLProtocol所拦截
已经确认到iOS10.2为止 WKWebView都不支持NSURLProtocol
本地HTML资源加载相关
iOS8:
先将本地 HTML 文件的数据 copy 到 tmp /www目录中,然后再使用 loadRequest 来加载。但是如果在 HTML 中加入了其他资源文件,例如 js,css,image 等也必须一同 copy 到 tmp /www目录 中。
iOS9及以后:
使用以下API进行加载
[WKWebView loadFileURL:allowingReadAccessToURL:]```
#跨域问题
WebKit框架对跨域进行了安全性检查限制,不允许跨域,比如从一个 HTTP 页对 HTTPS 发起请求是无效的。而系统的 Safari ,iOS 10出现的 SFSafariViewController 都是支持跨域的。
所以解决方法是实现WKNavigationDelegate中的
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;```
方法,在里面进行域名的判断,需要跨域的时候用SFSafariViewController去打开
网友评论