1. 加载方式
WKWebview 有三种方式可以加载html, 而你需要哪种,取决于html的存在方式.
1》如果html是通过服务器,以url的形式返回,则使用下面这种加载方式
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
补充: 如果加载url出现1002问题,需处理一下url的编码
[_urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
2》如果html为本地文件
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@“test.html" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
[self.webView loadRequest:request];
3》 除了上面之外的第三种 ----如:带标签的字符串
[self.webView loadHTMLString:@"<p>Hello</p>" baseURL:nil];
2. 对加载内容进行缩放
1》先设置WKWebview的相关属性,如下;
_contentWebView.scalesPageToFit = YES;
_contentWebView.multipleTouchEnabled = YES;
_contentWebView.userInteractionEnabled = YES;
_contentWebView.scrollView.scrollEnabled = YES;
_contentWebView.contentMode = UIViewContentModeScaleAspectFit;
2》然后在加载完成的代理方法中注入js,设置放大缩小的最大/最小尺寸
NSString *jsMeta =[NSString stringWithFormat:@"var meta = document.createElement('meta');meta.content='width=device-width,initial-scale=2.0,minimum-scale=0.5,maximum-scale=3';meta.name='viewport';document.getElementsByTagName('head')[0].appendChild(meta);"];
[webView stringByEvaluatingJavaScriptFromString:jsMeta];
注意: 如果是使用loadHTMLString 方式加载的html,需要注意是否带有完整的html标签,如果只是body中的内容,需要在加载方法之前先对字符串进行拼接,如下
3. WKWebview的手势与html的事件冲突(比如html的长按事件)
在webview加载完成(didFinishNavigation)中加入如下代码,将webview的选中事件禁掉。
[webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];
[webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];
4. 禁止/允许 点击html中的超链接(或者说,点击超链接禁止/允许跳转页面)
首先要设置代理: WKNavigtionDelegate
再实现代理方法: decidePolicyForNavigationAction (如果实现了这个代理方法,就必须得调用decisionHandler这个block,否则会导致app 崩溃)
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction: (WKNavigationAction *)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler {
NSURL *strRequest = navigationAction.request.URL;
// sourceFrame和targetFrame,分别代表这个方法的出处和目标。
if(navigationAction.targetFrame == nil){
decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转,
}else{
decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
}
}
5. 点击html中的图片,要求对图片进行缩放
1》 设置代理,在didFinishNavigation(加载完成)中注入js
2》实现页面开始加载的方法(didStartProvisionalNavigation)
6. 页面返回问题
1》html自带导航栏,点击返回跳转上一页(回到APP首页)
a: js 需要绑定返回事件:
var u=navigator.userAgent;
var isAndroid=u.indexOf('Android')>-1||u.indexOf('Adr')>-1;
var isiOS=!!u.match(/\(i[^;]+;(U;)?CPU.+Mac OS X/);
if(isAndroid){
androidToJs.close();
}else{ window.webkit.messageHandlers.AppLogout.postMessage('AppLogout’);
}
b: oc 注入js 的AppLogout 方法
WKWebViewConfiguration *config =[[WKWebViewConfiguration alloc]init];
//注册供js调用的方法
WKUserContentController * userContentController =[[WKUserContentController alloc]init];
//添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除
[userContentController addScriptMessageHandler:self name:@"AppLogout"];
config.userContentController = userContentController;
config.preferences.javaScriptEnabled = YES;//打开js交互
实现代理方法
-(void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
//如果是js注入的app退出事件,让js执行oc的方法
if([message.name isEqualToString:@"AppLogout"]){
if([self presentedViewController]){
[self dismissViewControllerAnimated:YES completion:nil];
} else {
if([_wkwebView canGoBack]){ //如果上一页还是html页面
[_wkwebView goBack];
}else{ //上一页返回到app
[self.navigationController popViewControllerAnimated:YES];
}
}
}
}
-(void)dealloc{
[[_webView configuration].userContentController removeScriptMessageHandlerForName:@"AppLogout"];
}
方法二: 通过第三方库:WebViewJavascriptBridge
js:
/*这段代码是固定的,必须要放到js中*/
functionsetupWebViewJavascriptBridge(callback){
if(window.WebViewJavascriptBridge){returncallback(WebViewJavascriptBridge);}
if(window.WVJBCallbacks){returnwindow.WVJBCallbacks.push(callback);}
window.WVJBCallbacks=[callback];
varWVJBIframe=document.createElement('iframe');
WVJBIframe.style.display='none';
WVJBIframe.src='wvjbscheme://__BRIDGE_LOADED__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function(){document.documentElement.removeChild(WVJBIframe)},0)
}
setupWebViewJavascriptBridge(function(bridge){
// 所有与iOS交互的JS代码放这里! bridge.callHandler('backAction',1,function(response){
log('JS got response',response)
})
})
oc:
self.bridge = [WebViewJavascriptBridge bridgeForWebView:_wkWebView];
//如果不需要实现,可以不设置
[self.bridge setWebViewDelegate:self];
[self.bridge registerHandler:@"backAction" handler:^(id data, WVJBResponseCallback responseCallback) {
[self.navigationController popViewControllerAnimated:YES];
}];
注: 该方法为js调用oc的 backAction 方法,返回上一级.
2》 原生导航栏: 返回html的上一级页面
app需要重写导航栏的返回方法,在方法中加上如下判断
if([_wkwebView canGoBack]){
[_wkwebView goBack];
}else{
[self.navigationController popViewControllerAnimated:YES];
}
7. 根据html的title 做判断(比如根据html的title显示/隐藏原生导航栏)
1》在初始化方法中给属性(title)添加观察者
[self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
2》实现方法
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change (NSDictionary*)change context:(void*)context {
if([keyPathisEqualToString:@"title"]){//网页title
if(object ==self.webView){
if([self.webView.titlecontainsString:@"错误页面"]) {
self.navigationController.navigationBar.hidden=NO;
}else{
self.navigationController.navigationBar.hidden=YES;
}
}
}
}
3》 页面消失时移除观察者
[self.webView removeObserver:self forKeyPath:@"title"];
8.
解决加载html时, alert 无效问题
在页面上加入以下方法即可
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void(^)(void))completionHandler{
//选择框
UIAlertController *alertController =[UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
completionHandler();
}])];
[self presentViewController:alertController animated:YES completion:nil];
//弹提示框
if(message){
[MBProgressHUD showAlert:message];
completionHandler();
}
}
-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void(^)(BOOL))completionHandler{
// DLOG(@"msg = %@ frmae = %@",message,frame);
UIAlertController *alertController =[UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action){
completionHandler(NO);
}])];
[alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
completionHandler(YES);
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void(^)(NSString * _Nullable))completionHandler{
UIAlertController *alertController =[UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField){
textField.text = defaultText;
}];
[alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
completionHandler(alertController.textFields[0].text?:@"");
}])];
[self presentViewController:alertController animated:YES completion:nil];
}