// // WKWebViewVC.m // PoliceHome // // Created by 刘惠萍 on 2020/12/15. // Copyright © 2020 刘惠萍. All rights reserved. // #import "WKWebViewVC.h" #import @interface WKWebViewVC () @property (nonatomic, strong) WKWebView * webView; ///网页加载进度视图 @property (nonatomic, strong) UIProgressView * progressView; /// WKWebView 内容的高度 @property (nonatomic, assign) CGFloat webContentHeight; @property (nonatomic, strong) BaseNavView *navView; @end @implementation WKWebViewVC - (BaseNavView *)navView{ if (!_navView) { _navView = [BaseNavView initNavBackTitle:UnPackStr(self.navStr) rightView:nil]; WEAKSELF _navView.blockBack = ^{ if (weakSelf.webView.canGoBack) { [weakSelf.webView goBack]; }else{ [GB_Nav popViewControllerAnimated:true]; } }; } return _navView; } #pragma mark - Override - (void)viewDidLoad { [super viewDidLoad]; if (self.isNav) { [self.view addSubview:self.navView]; } [self setupUI]; [self addKVO]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.progressView removeFromSuperview]; } - (void)dealloc { [self removeKVO]; [NSURLProtocol registerClass:[NSURLProtocol class]]; } #pragma mark - UI - (void)setupUI { self.view.backgroundColor = UIColor.whiteColor; //设置自定义Cookie在WKWebView初始化之前 [self.view addSubview:self.webView]; } #pragma mark - Getter - (WKWebView *)webView { if(_webView == nil){ //创建网页配置 WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, self.isNav?NAVIGATIONBAR_HEIGHT:0, SCREEN_WIDTH, self.isNav?SCREEN_HEIGHT-NAVIGATIONBAR_HEIGHT:self.isHight?SCREEN_HEIGHT-NAVIGATIONBAR_HEIGHT-W(55)-W(84):SCREEN_HEIGHT) configuration:config]; _webView.navigationDelegate = self; //以下代码适配文本大小 NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"; //用于进行JavaScript注入 WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; [config.userContentController addUserScript:wkUScript]; _webView.allowsBackForwardNavigationGestures = YES; if (self.isH5) { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:UnPackStr(self.htmlString)]]; [_webView loadRequest:request]; }else{ [_webView loadHTMLString:UnPackStr(self.htmlString) baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]]; } } return _webView; } - (UIProgressView *)progressView { if (!_progressView){ _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 2)]; _progressView.tintColor = [UIColor blueColor]; _progressView.trackTintColor = [UIColor clearColor]; } if (_progressView.superview == nil) { [self.navigationController.navigationBar addSubview:_progressView]; } return _progressView; } #pragma mark - KVO ///添加键值对监听 - (void)addKVO { //监听网页加载进度 [self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; } ///移除监听 - (void)removeKVO { //移除观察者 [_webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))]; [_webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(title))]; } //kvo监听 必须实现此方法 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == _webView) { NSLog(@"网页加载进度 = %f",_webView.estimatedProgress); self.progressView.progress = _webView.estimatedProgress; if (_webView.estimatedProgress >= 1.0f) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.progressView.progress = 0; }); } }else if([keyPath isEqualToString:@"title"] && object == _webView){ self.navStr = _webView.title; // [_navView changeTitle:UnPackStr(self.navStr)]; } } #pragma mark - Events Handle //返回上一步 - (void)goBackAction:(id)sender{ if (_webView.canGoBack) { [_webView goBack]; }else{ } } //前往下一步 - (void)goForwardAction:(id)sender{ [_webView goForward]; } #pragma mark - WKNavigationDelegate // 根据WebView对于即将跳转的HTTP请求头信息和相关信息来决定是否跳转 - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { //请求头信息 NSDictionary *allHTTPHeaderFields = [navigationAction.request allHTTPHeaderFields]; NSLog(@" UserAgent: %@",allHTTPHeaderFields[@"User-Agent"]); decisionHandler(WKNavigationActionPolicyAllow); } // 根据客户端受到的服务器响应头以及response相关信息来决定是否可以跳转 - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{ if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]] && [navigationResponse.response.URL.absoluteString isEqualToString:self.htmlString]) { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)navigationResponse.response; if (httpResponse.statusCode == 304) { //自上次请求后,文件还没有修改变化 //可以加载本地缓存 }else if (httpResponse.statusCode == 200){ // [SLMethod userDefaultsSetObject:httpResponse.allHeaderFields[@"Last-Modified"] forKey:@"localLastModified"]; NSLog(@" httpResponse:%@",httpResponse); } } //允许跳转 decisionHandler(WKNavigationResponsePolicyAllow); } // 页面加载完成之后调用 - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { } //进程被终止时调用 - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{ //当 WKWebView 总体内存占用过大,页面即将白屏的时候,系统会调用此7u776回调函数,我们在该函数里执行[webView reload](这个时候 webView.URL 取值尚不为 nil)解决白屏问题。在一些高内存消耗的页面可能会频繁刷新当前页面,H5侧也要做相应的适配操作。 [webView reload]; } @end