热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

WKWebview使用记录

1、WKWebview添加手势UISwipeGestureRecognizer*swipe[[UISwipeGestureRecognizeralloc]initWithTarg

1、WKWebview添加手势

UISwipeGestureRecognizer *swipe =[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction)];
swipe.delegate = self;
[wkWebView addGestureRecognizer:swipe];// 允许多个手势并发
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {return YES;
}

2、WKWebview禁用弹簧滑动

wkWebView.scrollView.bounces = NO;

3、WKWebview被js调用

window.webkit.messageHandlers.<对象名>.postMessage(body:<数据>)//body中可以直接放js对象,也可以省略body

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{NSLog(@"JS 调用了 %@ 方法,传回参数 %@",message.name,message.body);NSMutableDictionary *dic=[message.body objectForKey:@"body"];
}

4、WKWebview调用js

NSData *data=[NSJSONSerialization dataWithJSONObject:self->object options:NSJSONWritingPrettyPrinted error:nil];
NSString *dataJson=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];NSString *dataFunc=[NSString stringWithFormat:@"generalChart(%@,%lu)",dataJson,(unsigned long)self->chartType];[self evaluateJavascript:dataFunc completionHandler:^(id _Nullable param, NSError * _Nullable error) {}];

5、wkwebview手势返回抖屏问题:
webview侧滑返回后会接着触发html页面添加的transition动画导致

[wkWebView setAllowsBackForwardNavigationGestures:true];//设置手势返回

6、wkwebview无法跳转App Store

- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler
{WKNavigationActionPolicy policy =WKNavigationActionPolicyAllow;if([[navigationAction.request.URL host] isEqualToString:@"itunes.apple.com"] &&[[UIApplication sharedApplication] openURL:navigationAction.request.URL]){policy =WKNavigationActionPolicyCancel;}decisionHandler(policy);
}

wkwebview无法跳转企业安装

- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler
{NSString *strRequest = [navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];if ([strRequest containsString:@"itms-services"]) {[[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest]];}decisionHandler(policy);
}

7、wkwebview监听事件

[webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
[webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
[webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
// 进度条
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];// 只要观察的对象属性有新值就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{NSLog(@"%d, %d", self.webView.canGoForward, self.webView.canGoBack);
}

8、wkwebview关于iPhone X页面适配,全屏显示,发现顶部出现20px的空白
添加启动图
增加X启动图

AppDelegate的didFinishLaunchingWithOptions方法中添加

if (@available(iOS 11.0, *)) {[[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];}

webview添加

if (@available(iOS 11.0, *)) {wkWebView.scrollView.cOntentInsetAdjustmentBehavior= UIScrollViewContentInsetAdjustmentNever;
}else {self.edgesForExtendedLayout = UIRectEdgeNone;
}

9、wkwebview加载沙盒目录tem中html,从mainBundle拷贝文件夹到tem

NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"dist" ofType:@""];NSString *path = NSTemporaryDirectory();NSString *cacheStr=[NSString stringWithFormat:@"%@/dist",path];NSFileManager * defaultManager = [NSFileManager defaultManager];NSError *err = nil;[defaultManager copyItemAtPath: strResourcesBundle toPath:cacheStr error: &err];if(err){NSLog(@"复制初始资源文件出错:%@", err);}NSArray *cOntensArr= [NSArray arrayWithArray:[defaultManager contentsOfDirectoryAtPath:cacheStr error:nil]];NSLog(@"%@",contensArr);

wkwebview从tem目录下获取加载文件,生成url时使用fileURLWithPath

NSString *cachesPath = NSTemporaryDirectory();//tem文件目录
NSString *cacheStr=[NSString stringWithFormat:@"%@dist/index.html",cachesPath];
NSURL *url=[NSURL fileURLWithPath: cacheStr];
if (@available(iOS 9.0, *)) {[wkWebView loadFileURL:url allowingReadAccessToURL:url];
} else {[wkWebView loadRequest:[NSURLRequest requestWithURL:url]];
}

获取沙盒地址的方法

NSString *homeDir = NSHomeDirectory();// 获取沙盒主目录路径
NSString *cachesPath = NSTemporaryDirectory();//tem文件目录
NSString *cachesPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];//Documents文件目录

10、WKWebView加载不受信任的https造成错误:参考

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{NSLog(@"didReceiveAuthenticationChallenge");if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];completionHandler(NSURLSessionAuthChallengeUseCredential,card);}
}

11、WKWebView隐藏导航栏全屏加载,导航无法手势返回问题,开始以为与setAllowsBackForwardNavigationGestures手势冲突造成,排查后发现是导航隐藏后不支持手势返回,添加以下代码即可,更详细问题参考文章第2点。

隐藏导航代码

[self.navigationController setNavigationBarHidden:NO animated:NO];

支持手势返回代码

self.navigationController.interactivePopGestureRecognizer.delegate = self;self.navigationController.interactivePopGestureRecognizer.enabled = YES;

12、WKWebView设置setAllowsBackForwardNavigationGestures手势返回事件监听方法:

self.navigationController.interactivePopGestureRecognizer.delegate = self;

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{return YES;
}

13、WKWebView在iOS8中使用允许手势返回会报错

if (@available(iOS 9.0, *)) {[wkWebView setAllowsBackForwardNavigationGestures:true];
}

14、WKWebview在iOS11中的适配,顶部会让出状态栏高度

if (@available(iOS 11.0, *)) {wkWebView.scrollView.cOntentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
}

if (@available(iOS 11.0, *)) {[[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
}

15、设置WKWebview是否随键盘上移

//设置wkwebview是否可以随着键盘往上移
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{if (isAllowScrollZoom) {return wkWebView;}else{return nil;}
}

16、其它应用后台定位顶端蓝条,导致wkwebview页面向下移动

[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(didChangeStatusBarFrame:)name:UIApplicationDidChangeStatusBarFrameNotification object:nil];

- (void)didChangeStatusBarFrame:(NSNotification *)notification
{NSValue *statusBarFrameValue = [notification.userInfo valueForKey:UIApplicationStatusBarFrameUserInfoKey];NSLog(@"Status bar frame changed:%@", NSStringFromCGRect([statusBarFrameValue CGRectValue]));wkWebView.frame=CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
}

17、wkwebview在iOS12中键盘弹起页面不收回问题

/// 监听将要弹起[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow) name:UIKeyboardWillShowNotification object:nil];/// 监听将要隐藏[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHidden) name:UIKeyboardWillHideNotification object:nil];

//iOS12中键盘弹起页面不收回问题
#pragma mark - addObserverKeyboard
/// 键盘将要弹起
- (void)keyBoardShow {CGPoint point = wkWebView.scrollView.contentOffset;keyBoardPoint = point;
}
/// 键盘将要隐藏
- (void)keyBoardHidden {wkWebView.scrollView.cOntentOffset= keyBoardPoint;
}

18、wkwebview加载document目录下的文件

-(NSString *)temPathWithPath:(NSString *)path
{
// NSString *cachesPath = NSTemporaryDirectory();//tem文件目录
// NSString *cacheStr=[NSString stringWithFormat:@"%@%@",cachesPath,path];NSString *cachesPath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];NSString *cacheStr=[NSString stringWithFormat:@"%@/%@",cachesPath,path];return cacheStr;
}

NSString* webViewUrl=[[WBQmapHandle sharedQmapHandle]temPathWithPath:@"App/dist/index.html"];NSString* accessUrl = [[WBQmapHandle sharedQmapHandle]temPathWithPath:@"App/dist"];NSURL *url=[NSURL fileURLWithPath:webViewUrl];NSURL *aurl = [NSURL fileURLWithPath:accessUrl]; // 权限,目录文件夹,不写访问不到资源if (@available(iOS 9.0, *)) {[wkWebView loadFileURL:url allowingReadAccessToURL:aurl];} else {[wkWebView loadRequest:[NSURLRequest requestWithURL:url]];}

19、wkwebview注入js文件到web

NSString *filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"bridge.js"];
NSString *jsString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"读取的js:%@", jsString);
NSMutableString *Javascript = [NSMutableString string];
[Javascript appendString:jsString];
WKUserScript *nOneSelectScript= [[WKUserScript alloc] initWithSource:Javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

20、wkwebview支持横竖屏切换

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{NSLog(@"UIViewController will rotate to Orientation: %ld", toInterfaceOrientation);NSInteger | ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)){//横屏NSLog(@"横屏");wkWebView.frame = CGRectMake(0, 0, height, width);}else{//竖屏NSLog(@"竖屏");wkWebView.frame = CGRectMake(0, 0, height, width);}
}

持续更新中…


推荐阅读
author-avatar
liujiayan0529_584
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有