// // TFWebViewController.m // WXReader // // Created by 谢腾飞 on 2020/12/3. // Copyright © 2020 xtfei_2011@126.com. All rights reserved. // #import "TFWebViewController.h" #import "TFScriptMessageHandler.h" #import "TFShareManager.h" #import #import #import "NSObject+Observer.h" static void *WkWebBrowserContext = &WkWebBrowserContext; @interface TFWebViewController () @property (nonatomic, strong) WKWebView *webView; @property (nonatomic, strong) UIProgressView *progressView; @property (nonatomic, strong) NSMutableArray *snapShotsArray; //返回按钮 @property (nonatomic, strong) UIButton *customBackButton; //关闭按钮 @property (nonatomic, strong) UIButton *closeButton; @end @implementation TFWebViewController - (void)viewDidLoad { [super viewDidLoad]; [self initialize]; [self createSubviews]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Hidden_Tabbar object:@"1"]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.webView setNavigationDelegate:nil]; [self.webView setUIDelegate:nil]; NSArray *t_arr = self.navigationController.viewControllers; if (t_arr.count == 0) { [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Show_Tabbar object:nil]; } } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self setStatusBarDefaultStyle]; } - (void)initialize { [self setNavigationBarTitle:self.navTitle]; [self hiddenNavigationBarLeftButton]; [self.navigationBar addSubview:self.customBackButton]; [self.navigationBar addSubview:self.closeButton]; [self.view addSubview:self.webView]; [self.view addSubview:self.progressView]; } - (void)createSubviews { NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [self.webView loadRequest:request]; } - (void)customBackItemClicked { if (self.webView.goBack) { [self.webView goBack]; } else { if (self.isPresentState) { [self dismissViewControllerAnimated:YES completion:nil]; } else { [self.navigationController popViewControllerAnimated:YES]; } } } - (void)closeItemClicked { if (self.isPresentState) { [self dismissViewControllerAnimated:YES completion:nil]; } else { [self.navigationController popViewControllerAnimated:YES]; } } - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { if ([message.name isEqualToString:@"share"]) { NSDictionary *dic = [TFUtilsHelper dictionaryWithJsonString:message.body]; NSString *title = [TFUtilsHelper formatStringWithObject:[dic objectForKey:@"title"]]; NSString *desc = [TFUtilsHelper formatStringWithObject:[dic objectForKey:@"desc"]]; NSString *imageUrl = [TFUtilsHelper formatStringWithObject:[dic objectForKey:@"image"]]; NSString *url = [TFUtilsHelper formatStringWithObject:[dic objectForKey:@"url"]]; [TFShareManager shareWithTitle:title desc:desc imageUrl:imageUrl shareUrl:url]; } } // 这个是网页加载完成,导航的变化 - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; [self updateNavigationItems]; } // 开始加载 - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { self.progressView.hidden = NO; } // 内容返回时调用 - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {} // 服务器请求跳转的时候调用 - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {} - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { switch (navigationAction.navigationType) { case WKNavigationTypeLinkActivated: { [self pushCurrentSnapshotViewWithRequest:navigationAction.request]; break; } case WKNavigationTypeFormSubmitted: { [self pushCurrentSnapshotViewWithRequest:navigationAction.request]; break; } case WKNavigationTypeBackForward: { break; } case WKNavigationTypeReload: { break; } case WKNavigationTypeFormResubmitted: { break; } case WKNavigationTypeOther: { [self pushCurrentSnapshotViewWithRequest:navigationAction.request]; break; } default: { break; } } [self updateNavigationItems]; decisionHandler(WKNavigationActionPolicyAllow); } // 内容加载失败时候调用 - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {} // 跳转失败的时候调用 - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {} // 进度条 - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {} - (void)updateNavigationItems { if (self.webView.canGoBack) { self.closeButton.hidden = NO; }else{ self.navigationController.interactivePopGestureRecognizer.enabled = YES; self.closeButton.hidden = YES; } } // 请求链接处理 - (void)pushCurrentSnapshotViewWithRequest:(NSURLRequest *)request { NSURLRequest *lastRequest = (NSURLRequest *)[[self.snapShotsArray lastObject] objectForKey:@"request"]; if ([request.URL.absoluteString isEqualToString:@"about:blank"]) { return; } if ([lastRequest.URL.absoluteString isEqualToString:request.URL.absoluteString]) { return; } UIView *currentSnapShotView = [self.webView snapshotViewAfterScreenUpdates:YES]; [self.snapShotsArray addObject:@{@"request":request,@"snapShotView":currentSnapShotView}]; } - (UIButton *)customBackButton { if (!_customBackButton) { UIButton *backButton = [[UIButton alloc] init]; backButton.frame = CGRectMake(kHalfMargin, PUB_NAVBAR_OFFSET + 20, 44, 44); [backButton.titleLabel setFont:kMainFont]; [backButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; [backButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted]; [backButton setImage:[UIImage imageNamed:@"public_back"] forState:UIControlStateNormal]; [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 6, 12, 18)]; [backButton addTarget:self action:@selector(customBackItemClicked) forControlEvents:UIControlEventTouchUpInside]; _customBackButton = backButton; } return _customBackButton; } - (UIButton *)closeButton { if (!_closeButton) { UIButton *backButton = [[UIButton alloc] init]; backButton.frame = CGRectMake(kHalfMargin + 44, PUB_NAVBAR_OFFSET + 20, 44, 44); backButton.hidden = YES; backButton.adjustsImageWhenHighlighted = NO; backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; [backButton setTitle:TFLocalizedString(@"关闭") forState:UIControlStateNormal]; [backButton.titleLabel setFont:kMainFont]; [backButton setTitleColor:kBlackColor forState:UIControlStateNormal]; [backButton addTarget:self action:@selector(closeItemClicked) forControlEvents:UIControlEventTouchUpInside]; _closeButton = backButton; } return _closeButton; } - (WKWebView *)webView { if (!_webView) { WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; if (@available(iOS 9.0, *)) { configuration.allowsAirPlayForMediaPlayback = YES; } configuration.allowsInlineMediaPlayback = YES; configuration.selectionGranularity = YES; configuration.processPool = [[WKProcessPool alloc] init]; configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES; configuration.suppressesIncrementalRendering = YES; configuration.userContentController = [WKUserContentController new]; [configuration.userContentController addScriptMessageHandler:[[TFScriptMessageHandler alloc] initWithDelegate:self] name:@"handleGoMall"]; _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, PUB_NAVBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - PUB_NAVBAR_HEIGHT) configuration:configuration]; _webView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]; _webView.navigationDelegate = self; _webView.UIDelegate = self; WS(weakSelf) [_webView addObserver:NSStringFromSelector(@selector(estimatedProgress)) complete:^(WKWebView * _Nonnull obj, id _Nullable oldVal, id _Nullable newVal) { [weakSelf.progressView setAlpha:1.0f]; BOOL animated = obj.estimatedProgress > weakSelf.progressView.progress; [weakSelf.progressView setProgress:obj.estimatedProgress animated:animated]; if (obj.estimatedProgress >= 1.0f) { [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{ [weakSelf.progressView setAlpha:0.0f]; } completion:^(BOOL finished) { [weakSelf.progressView setProgress:0.0f animated:NO]; }]; } }]; _webView.allowsBackForwardNavigationGestures = YES; } return _webView; } - (UIProgressView *)progressView { if (!_progressView) { _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; _progressView.frame = CGRectMake(0, PUB_NAVBAR_HEIGHT, self.view.bounds.size.width, 3); _progressView.progressTintColor = kMainColor; [_progressView setTrackTintColor:[UIColor clearColor]]; } return _progressView; } - (NSMutableArray *)snapShotsArray { if (!_snapShotsArray) { _snapShotsArray = [NSMutableArray array]; } return _snapShotsArray; } - (void)dealloc { [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"handleGoMall"]; } @end