0、WKWebview加载在线网页,解决中文乱码

NSString*str = [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL * urlstr= [NSURL URLWithString:str];
[_wkWebView loadRequest:[NSMutableURLRequest requestWithURL:urlstr cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15]];

上面如果包含#的url会出现问题,使用下面的方法

- (NSString *)strUTF8Encoding:(NSString *)str {return [[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] stringByReplacingOccurrencesOfString:@"%23" withString:@"#"];
}

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<NSKeyValueChangeKey,id> *)change context:(void *)context
{NSLog(@"%d, %d", self.webView.canGoForward, self.webView.canGoBack);
}

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

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和iOS10中的适配,顶部会让出状态栏高度

if (@available(iOS 11.0, *)) {wkWebView.scrollView.contentInsetAdjustmentBehavior =UIScrollViewContentInsetAdjustmentNever;
} else {self.edgesForExtendedLayout = UIRectEdgeNone;
}
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支持横竖屏切换
单页面支持旋转参考1、参考2

# pragma mark 支持横竖屏幕转换
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{NSLog(@"UIViewController will rotate to Orientation: %ld", toInterfaceOrientation);if(([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)){//横屏NSLog(@"横屏");[self transformWkWebViewFrame];}else{//竖屏NSLog(@"竖屏");[self transformWkWebViewFrame];}
}
// 进入其他页面改变方向后,返回当前页面刷新布局
-(void)refreshWkWebViewFrame {NSInteger  width=self.view.frame.size.width;NSInteger  height=self.view.frame.size.height;self.wkWebView.frame = CGRectMake(0, 0, width, height);
}
// 根据旋转方向改变布局
-(void)transformWkWebViewFrame {NSInteger  width=self.view.frame.size.width;NSInteger  height=self.view.frame.size.height;self.wkWebView.frame = CGRectMake(0, 0, height, width);
}

当进入其他页面翻转屏幕后返回该页面要刷新当前页面frame布局

- (void)viewWillAppear:(BOOL)animated
{[super viewWillAppear:animated];[self refreshWkWebViewFrame];
}

其他要注意的,如果导航栏出现黑线框,布局时需要动态判断状态栏高度

CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
if(([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)){//横屏NSLog(@"横屏");_wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0.0f, rectStatus.size.height+44, self.view.frame.size.width, self.view.frame.size.height-rectStatus.size.height-44)];}else{//竖屏NSLog(@"竖屏");_wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0.0f, rectStatus.size.height+20, self.view.frame.size.width, self.view.frame.size.height-rectStatus.size.height-20)];
}

21、wkwebview混合开发进入后台页面白屏解决方案

- (void)applicationDidBecomeActive:(UIApplication *)application {// 进入前台前先调用判断wkwebview是否白屏,从新初始化wkwebviewUIViewController* currentView = self.window.visibleViewController;if ([[currentView class] isSubclassOfClass:[HomeViewController class]]) {[(HomeViewController*)currentView resetWindown];}
}
-(void)resetWindown {// 如果当前页面进入后台后白屏重新初始化webview, 延时为了避免首次启动重复调用初始化dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{if (wkWebView && [self isBlankView:self.view]) {[self initWebview];}});
}
// 判断是否白屏
// 参考文章https://www.jianshu.com/p/de67f5a752b6
- (BOOL)isBlankView:(UIView*)view { // YES:blankClass wkCompositingView =NSClassFromString(@"WKCompositingView");if ([view isKindOfClass:[wkCompositingView class]]) {return NO;}for(UIView *subView in view.subviews) {if (![self isBlankView:subView]) {return NO;}}return YES;
}

22、wkwebview加载本地html带hash路由无效果
fileURLWithPath会把#和?进行转码导致加载不出页面,改用下面代码进行手动拼接即可,核心代码如下处理

-(void)loadWebviewUrl:(NSString *)webViewUrl {NSString *htmlPath = [NSString stringWithFormat:@"file://%@", webViewUrl];NSURL *url=[NSURL URLWithString:htmlPath];NSURL *aurl = [NSURL fileURLWithPath:_accessUrl];if (@available(iOS 9.0, *)) {[wkWebView loadFileURL:url allowingReadAccessToURL:aurl];} else {[wkWebView loadRequest:[NSURLRequest requestWithURL:url]];}
}

完整加载本地html代码如下

-(void)reloadWebview{NSFileManager *mgr = [NSFileManager defaultManager];NSArray *subpaths = [mgr subpathsAtPath:[[WBQmapHandle sharedQmapHandle]temPathWithPath:@"App"]];NSString *archiveName = [subpaths count] ? [subpaths objectAtIndex:0] : @"dist";if ([[WBQmapHandle sharedQmapHandle]temIsFileExist:[NSString stringWithFormat:@"App/%@/index.html", archiveName]]) {_webViewUrl=[[WBQmapHandle sharedQmapHandle]temPathWithPath:[NSString stringWithFormat:@"App/%@/index.html", archiveName]];_accessUrl = [[WBQmapHandle sharedQmapHandle]temPathWithPath:[NSString stringWithFormat:@"App/%@", archiveName]];[self loadWebviewUrl:_webViewUrl];}
}
-(NSString *)getWebviewUrl: (NSString *)path {return [NSString stringWithFormat:@"%@?#/%@", _webViewUrl, path];
}
-(void)loadWebviewUrl:(NSString *)webViewUrl {NSString *htmlPath = [NSString stringWithFormat:@"file://%@", webViewUrl];NSURL *url=[NSURL URLWithString:htmlPath];NSURL *aurl = [NSURL fileURLWithPath:_accessUrl];if (@available(iOS 9.0, *)) {[wkWebView loadFileURL:url allowingReadAccessToURL:aurl];} else {[wkWebView loadRequest:[NSURLRequest requestWithURL:url]];}
}

23、wkwebview删除缓存


- (void)deleteWebCache {/*在磁盘缓存上。WKWebsiteDataTypeDiskCache,html离线Web应用程序缓存。WKWebsiteDataTypeOfflineWebApplicationCache,内存缓存。WKWebsiteDataTypeMemoryCache,本地存储。WKWebsiteDataTypeLocalStorage,CookiesWKWebsiteDataTypeCookies,会话存储WKWebsiteDataTypeSessionStorage,IndexedDB数据库。WKWebsiteDataTypeIndexedDBDatabases,查询数据库。WKWebsiteDataTypeWebSQLDatabases*///    NSArray * types=@[WKWebsiteDataTypeDiskCache,WKWebsiteDataTypeOfflineWebApplicationCache, WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeIndexedDBDatabases,WKWebsiteDataTypeWebSQLDatabases];////    NSSet *websiteDataTypes= [NSSet setWithArray:types];NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{}];
}

持续更新中…

WKWebview使用记录相关推荐

  1. #iOS问题记录#WKWebView 闪退异常

    #iOS问题记录#WKWebView 闪退异常 参考文章: (1)#iOS问题记录#WKWebView 闪退异常 (2)https://www.cnblogs.com/Sanje3000/p/6953 ...

  2. 记录苹果构建吃包,苹果报itms-90809,cordova 需要将UIWebView转为WKWebView

    记录苹果构建吃包,苹果报itms-90809,cordova 需要将UIWebView转为WKWebView 参考链接 步骤 1. 添加cordova-ios 需要是5.1.1 以上 2.增加cord ...

  3. wkwebview css 动画,IOS WKWebview踩坑记录

    webview崩溃不会crash而是会白屏 在UIWebview中,进行了对性能影响过大的操作(例如图片特别的多,然后突然改变了css.调整页面字体,导致重绘:连续点击打开多个webview),App ...

  4. iOS WKWebView白屏检测演进方案记录

    网上查到的方案 typedef NS_ENUM(NSUInteger,webviewLoadingStatus) {WebViewNormalStatus = 0, //正常WebViewErrorS ...

  5. UIWebView、WKWebView使用详解及性能分析

    一.整体介绍 UIWebView自iOS2就有,WKWebView从iOS8才有,毫无疑问WKWebView将逐步取代笨重的UIWebView.通过简单的测试即可发现UIWebView占用过多内存,且 ...

  6. Swift WKWebView读取本地html

    哈喽,大家好    最近闲着无聊,学下Swift   以后会把一些知识点记录在这,以备用 废话不多说,直接上代码 /** WKWebView 的简单使用,读取本地html文件 */ let webVi ...

  7. web加载本地html,WKWebview加载本地html问题汇总

    最近做的功能,有部分逻辑是h5实现的,我们采用了本地+网络的机制来提高h5的显示速度,首先说一下机制, 1.本地存在一份html文件+校验码 2.程序启动获取远程校验码 3.远程校验码与本地校验码,比 ...

  8. ios图文详情加载html_IOS WKWebView加载本地H5以及css,js等样式

    两点非常坑爹的地方:第一点,就是导入前端给你的h5包的时候 导入h5的包 这里如果选择第一个,会无法加载js和css样式以及img,因为大部分前端这些东西都是写的绝对路径.如果你要选第一个groups ...

  9. WKWebView - 1

    最近项目打算将所有的UIWebView升级至WKWebView,在这里收集一下这几天学习的心得体会: 关于学习资料,网上很多,就不提了,可以参考这几位大大的: 超级详细: http://www.cnb ...

最新文章

  1. 【×××系列八】Dynamic Multipoint *** for IPv6 详解
  2. 对delegate进行扩展 打造通用的计时完成方法
  3. python三层装饰器-python三大神器===》装饰器
  4. hdu1999 不可摸数 好题.
  5. 4.Eclipse的安装和使用
  6. 智能合约重构社会契约(9)Fabric
  7. c++ :MFC 如何遍历窗口同类型控件ID
  8. 品质标签分几种颜色_北京标签不干胶印刷厂
  9. 软件测试2019:第七次作业
  10. CCF201703-3 Markdown(100分)【文本处理】
  11. eclipse安装activiti 工作流插件
  12. AppWeb服务后台登陆及配置的方法解答
  13. 效率源希捷硬盘修复(4.2版)及程序下载
  14. steam怎么解除共享_如何启用Steam家庭共享(及其功能)
  15. 能不能过?(C++)
  16. win10如何合并硬盘分区
  17. 速学计算机,新手电脑配置速成学习
  18. Python turtle入门:用小海龟画美队盾牌 (内附画五角星的详细代码)
  19. Safari 手机浏览器无法下载的问题
  20. Oracle11g新特性密码延迟验证的坑

热门文章

  1. 2021.12.26 第一章. 计算机组成与体系结构
  2. 伦敦 quant_伦敦统一用户组8
  3. VOLTE注册失败案例
  4. 网易互娱AI研究工程师实习生一面——记人生的第一次面试
  5. webview在android8.0,解决Android8.0系统应用打开webView报错
  6. js模板字符串自定义类名_详解JavaScript ES6中的模板字符串
  7. js打印window.print()图片打印
  8. 【Verilog数字系统设计——完成如下公式所表示的逻辑功能模块】
  9. 果园节水灌溉能否实现远程智能控制
  10. 做业务的程序猿如何提升技能?