美文网首页
iOS 搭建WKWebView框架

iOS 搭建WKWebView框架

作者: 风雨彩虹_123 | 来源:发表于2019-07-27 19:45 被阅读0次

前言

最近在项目中使用WKWebView遇到以下几个问题。

  • H5界面在APP中和浏览器中有两种展现形式,那我们加载时要怎样加载正确的界面呢?
  • 在H5界面中部分步骤怎样隐藏系统导航栏?
  • H5在未登录情况下会调用原生login,登录成功后怎样设置cookie?
  • H5调用原生后怎样回传信息?

WKWebView简单实用

在应用中我们不可避免的要加载H5界面用于展示,下面代码只是简单加载。

#import "ViewController.h"
#import <WebKit/WebKit.h>

@interface ViewController ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic, strong)WKWebView *webView;
@property(strong, nonatomic) UIProgressView *progressView;


@end

@implementation ViewController
- (WKWebView *)webView {
    if (!_webView) {
        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        _webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];
        //主要处理JS脚本,确认框,警告框等
        _webView.UIDelegate = self;
        //导航的代理
        _webView.navigationDelegate = self;
        //添加监测网页加载进度的观察者
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        //添加监测网页标题title的观察者
        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}
- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.frame = CGRectMake(0, 64, self.webView.frame.size.width, 2);
        _progressView.trackTintColor = [UIColor clearColor];
        _progressView.progressTintColor = [UIColor redColor];
        [_progressView setProgress:0.1 animated:YES];
    }
    return _progressView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.webView];
    self.webView.frame = CGRectMake(0, 0, 375, 667);
    [self.webView addSubview:self.progressView];
    NSString *url = @"https://www.baidu.com";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [self.webView loadRequest:request];
}
# pragma mark --- 获得h5的title显示
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    NSLog(@"页面结束加载");
    NSString *jsStr = [NSString stringWithFormat:@"document.title"];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSString *title = result;
        if (title.length > 6) {
            title = [title substringWithRange:NSMakeRange(0, 6)];
            title = [title stringByAppendingString:@"..."];
        }
        self.title = title;
    }];
}
# pragma mark --- kvo监听实现
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:newprogress animated:YES];
            __weak typeof(self) weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(),^{
                weakSelf.progressView.hidden = YES;
                [weakSelf.progressView setProgress:0 animated:NO];
            });
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }else if([keyPath isEqualToString:@"title"]) {
        
    }
}

WKWebView有2大代理,WKUIDelegate是用于显示UI的代理,WKNavigationDelegate的代理方法比价多,可以帮助我们做很多的处理,比如页面开始加载H5需要做的逻辑处理,在发送请求之前,决定是否跳转
等等。下面是WKNavigationDelegate代理执行的顺序。

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    //在发送请求之前,决定是否跳转
    decisionHandler(WKNavigationActionPolicyAllow);    
}

这个代理方法是加载网页第一个执行的方法,它可以确定是否加载这个网页。这里有一个枚举WKNavigationActionPolicy,在WebKit源码中的结构如下

/*! @enum WKNavigationActionPolicy
 @abstract The policy to pass back to the decision handler from the
 webView:decidePolicyForNavigationAction:decisionHandler: method.
 @constant WKNavigationActionPolicyCancel   Cancel the navigation.
 @constant WKNavigationActionPolicyAllow    Allow the navigation to continue.
 */
typedef NS_ENUM(NSInteger, WKNavigationActionPolicy) {
    WKNavigationActionPolicyCancel,
    WKNavigationActionPolicyAllow,
} API_AVAILABLE(macosx(10.10), ios(8.0));

根据上面的枚举值,我们可以做一些网页屏蔽或只加载想要的网页,代码如下

//在发送请求之前,决定是否跳转
     NSURL * url = navigationAction.request.URL;
    if ([url.absoluteString containsString:@""]) {
        //此处可以根据正则表达式进行屏蔽一些网页
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        if ([url.absoluteString containsString:@""]) {
            //此处可以根据特定URL做出相应的逻辑跳转,例如在URL中检测到order字段,就可以调到APP对应的订单模块。
        }
        decisionHandler(WKNavigationActionPolicyAllow);
    }

还有2个比较常用的代理方法是页面开始加载和页面加载结束,我们可以在这两个代理方法里面我们可以添加web加载动画

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    // 页面开始加载时调用
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    // 页面加载完成之后调用   
}

还有些代理方法我就不一一列举了,根据具体需求去调用相应的代理。

JS和OC的交互

在Webkit库中有一个WKScriptMessageHandler代理和WKUserContentController类,当webView遵守代理,就可以捕捉到JS消息的回调,WKUserContentController类主要是负责注册JS方法,设置处理接收JS方法的代理。

 //这个类主要用来做native与JavaScript的交互管理
   //    WKUserContentController * wkUController = [[WKUserContentController alloc] init];
//    //注册一个name为jsToOcNoPrams的js方法,设置处理接收JS方法的代理
//    [wkUController addScriptMessageHandler:self  name:@"jsToOcNoPrams"];
//    [wkUController addScriptMessageHandler:self  name:@"jsToOcWithPrams"];
//    config.userContentController = wkUController;
[[self.webView configuration].userContentController addScriptMessageHandler:self name:@"shareFriend"];
    [[self.webView configuration].userContentController addScriptMessageHandler:self name:@"getUrlInfo"];

 //通过接收JS传出消息的name进行捕捉的回调方法  js调OC
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
}

在上面我们看到注册JS方法可以有2中写法,方法二是比较常用的写法。[self.webView configuration] 获得就是WKUserContentControlle的实例对象,[self.webView configuration].userContentController 是将实例对象加载到webView上。添加一个监控导航显示的方法,当JS发送true是,就可以隐藏系统导航栏,不过要改变webView的frame,因为状态栏会遮住一部分内如。

那OC怎么调用JS呢?

其实这个很简单的,废话不多说直接上代码吧!

//OC调用JS  sendSuccess()是JS方法名,completionHandler是异步回调block
    NSString *jsString = [NSString stringWithFormat:@"sendSuccess('%@')", @"我成功啦!"];
    [_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
    }];

现在混合开发的应用程序越来越多,H5与原生的交互就是必须的了,有些功能是必须登录才可以使用的,那H5怎样获取登录状态。
在UIWebView中,在每次请求之前,会将NSHTTPCookieStorage里面的cookie自动添加到请求中,但是WKWebView中并不会自动向请求中添加cookie。这时就会出现一个问题,在H5界面中点击需要登录才能浏览的功能时,JS会调用原生的登录方法,登录成功后就把tocken标识添加到cookie中,并且刷新webView界面,这样H5就可以判断登录状态了,理想很美好,现实很残酷,进过多次测试H5就是拿不到登录状态。使用pod 'GGWkCookie'三方可以完美解决上面的问题。直接上代码吧!

//添加一个监听登录成功的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];

- (NSDictionary *)webviewSetAppCookieKeyAndValue {
    NSString *token = [ZBXSingleData shareInstance].userInfo.token;
    NSLog(@"-----%@",token);
    if (!token) {
        token = @"";
    }
    return @{
             @"JSESSIONID":token,
             };
}
- (void)loginSuccess {
    [self.detailWebView reloadCookie];
    [self.detailWebView reload];
}

就上面一点代码,完美解决webView的cookie的问题。是不是很清爽。

原生APP嵌套H5界面,要区分打开H5是在本地APP还是在手机浏览器,前端伙伴说需要配合修改默认的 UserAgent,以便区分

  //    要区分打开H5是在本地APP还是在手机浏览器,前端伙伴说需要配合修改默认的 UserAgent,以便区分。
    //    修改全局UserAgent值(这里是在原有基础上拼接自定义的字符串)
   NSString *  kSoftVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    if (@available(iOS 12.0, *)){
        NSString *baseAgent = @"Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15F79";
        NSString *newUserAgent = [baseAgent stringByAppendingString:[NSString stringWithFormat:@"zbxapp:/%@", kSoftVersion]];
        [self.detailWebView setCustomUserAgent:newUserAgent];
    }
    __weak typeof(self) weakSelf = self;
    [self.detailWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSString *userAgent = result;
        NSString *newUserAgent = [userAgent stringByAppendingString:[NSString stringWithFormat:@"zbxapp:/%@", kSoftVersion]];
        if (@available(iOS 9.0, *)) {
            [weakSelf.detailWebView setCustomUserAgent:newUserAgent];
        } else {
            [weakSelf.detailWebView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
        }
    }];

UA对于网站开发人员来说很熟悉,我们经常在HTTP请求的请求头中可以看到User-Agent这一字段,UA是一个特定的字符串,它通常包含了发送请求端的应用程序类型、操作系统、软件供应商以及软件的修订版本等信息。在实际使用中我们可以通过设置不同的UA来获取到不同的网页数据。
下面是全部代码

#import <UIKit/UIKit.h>
@interface WebViewController : UIViewController
- (instancetype)initWithAddress:(NSString *)urlString;

@end


#import "WebViewController.h"
#import <WebKit/WebKit.h>
#import <GGWkCookie/GGWkCookie.h>
@interface WebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,GGWkWebViewDelegate>
@property (nonatomic, strong) WKWebView *detailWebView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UIButton *collectButton;
@property (nonatomic, strong) UIImageView *lodingView;
@property (nonatomic, strong) UIView *loadingBackView;
@property(strong, nonatomic) UIBarButtonItem *navigationBackBarButtonItem;
@property(strong, nonatomic) UIBarButtonItem *navigationCloseBarButtonItem;

@end


@implementation ProduceDetailWebViewController

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_detailWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [_detailWebView removeObserver:self forKeyPath:@"scrollView.contentOffset"];
    [_detailWebView removeObserver:self forKeyPath:@"URL"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationItem setLeftBarButtonItems:@[self.navigationBackBarButtonItem] animated:NO];
    [self.view addSubview:self.detailWebView];
    //设置UA,区分是APP加载还是浏览器加载
    [self webViewH5String];
    self.detailWebView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kNavHeight - kSafeAreaBottomHeight);
    [self.detailWebView addSubview:self.progressView];
    //设置导航栏标题颜色,字号
    NSDictionary *textAttributes = @{
                                     NSFontAttributeName : [UIFont systemFontOfSize:18],
                                     NSForegroundColorAttributeName : HEXCOLOR(0x333333),
                                     };
    [self.navigationController.navigationBar setTitleTextAttributes:textAttributes];
    self.navigationItem.title = @"产品详情";
    
    //右侧分享按钮
    UIButton *rightBtn1 = [MYCommonHelper commonButtonWithTitle:nil color:nil font:nil backgroundImage:[UIImage imageNamed:@"share_icon_black"] target:self action:@selector(shareClicked:)];
    rightBtn1.size = CGSizeMake(40, 40);
    
    //右侧收藏按钮
    UIButton *rightBtn2 = [MYCommonHelper commonButtonWithTitle:nil color:nil font:nil backgroundImage:[UIImage imageNamed:@"collect_icon_black"] target:self action:@selector(collectClicked:)];
    _collectButton = rightBtn2;
    rightBtn2.size = CGSizeMake(40, 40);
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithCustomView:rightBtn1];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithCustomView:rightBtn2];
  
    self.navigationItem.rightBarButtonItems = @[item1,item2];
    
    //添加一个监听登录成功的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];
    
    //设置cookie的代理
    self.detailWebView.cookieDelegate = self;
    [self.detailWebView startCustomCookie];
}
- (NSDictionary *)webviewSetAppCookieKeyAndValue {
    NSString *token = [ZBXSingleData shareInstance].userInfo.token;
    NSLog(@"-----%@",token);
    if (!token) {
        token = @"";
    }
    return @{
             @"JSESSIONID":token,
             };
}
- (void)loginSuccess {
    [self.detailWebView reloadCookie];
    [self.detailWebView reload];
}

#pragma mark --- 左侧返回上一级按钮
- (UIBarButtonItem *)navigationBackBarButtonItem {
    if (_navigationBackBarButtonItem) return _navigationBackBarButtonItem;
    UIImage *backItemImage = [UIImage imageNamed:@"nav_icon_back"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:backItemImage style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    _navigationBackBarButtonItem = item;
    _navigationBackBarButtonItem.tintColor = [UIColor blackColor];
    return _navigationBackBarButtonItem;
}

#pragma mark --- 关闭Web按钮
- (UIBarButtonItem *)navigationCloseBarButtonItem {
    if (_navigationCloseBarButtonItem) return _navigationCloseBarButtonItem;
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(0, 0, 40, 40);
    [closeBtn setImage:[UIImage imageNamed:@"delete_icon_black"] forState:normal];
    [closeBtn addTarget:self action:@selector(navigationIemHandleClose:) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setContentEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 20)];
    
    _navigationCloseBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:closeBtn];
    
    return _navigationCloseBarButtonItem;
}
#pragma mark -- 关闭web按钮响应事件
- (void)navigationIemHandleClose:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark ---返回上一级按钮响应事件
- (void)back:(UIBarButtonItem *)sender
{
    [self.view resignFirstResponder];
    if ([self.detailWebView canGoBack]) {
        [self.detailWebView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark ---  分享事件
- (void)shareClicked:(UIButton *)btn{

}
#pragma mark --- 收藏事件
- (void)collectClicked:(UIButton *)btn{
    
}

#pragma mark --- 区分APP加载还是浏览器加载
-(void)webViewH5String{
    
    //要区分打开H5是在本地APP还是在手机浏览器
    NSString *  kSoftVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    if (@available(iOS 12.0, *)){
        NSString *baseAgent = @"Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15F79";
        NSString *newUserAgent = [baseAgent stringByAppendingString:[NSString stringWithFormat:@"zbxapp:/%@", kSoftVersion]];
        [self.detailWebView setCustomUserAgent:newUserAgent];
    }
    __weak typeof(self) weakSelf = self;
    [self.detailWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSString *userAgent = result;
        NSString *newUserAgent = [userAgent stringByAppendingString:[NSString stringWithFormat:@"zbxapp:/%@", kSoftVersion]];
        if (@available(iOS 9.0, *)) {
            [weakSelf.detailWebView setCustomUserAgent:newUserAgent];
        } else {
            [weakSelf.detailWebView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
        }
    }];
}

//监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            //结束动画
            [self endLoadingView];
            [self.progressView setProgress:newprogress animated:YES];
            __weak typeof(self) weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(),^{
                weakSelf.progressView.hidden = YES;
                [weakSelf.progressView setProgress:0 animated:NO];
            });
        }else {
            //加载动画
            [self showLoadingView];
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }else if ([keyPath isEqualToString:@"URL"]) {
        // 可以在这里进行拦截并做相应的处理
        
    }else {
        
    }
    [self updateNavigationItems];
}

# pragma mark --- 判断是否显示关闭web按钮
- (void)updateNavigationItems {
    [self.navigationItem setLeftBarButtonItems:nil animated:NO];
    // Web view can go back means a lot requests exist.
    if (_detailWebView.canGoBack || _detailWebView.backForwardList.backItem) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        if (self.navigationController.viewControllers.count == 1) {
            NSMutableArray *leftBarButtonItems = [NSMutableArray arrayWithArray:@[self.navigationBackBarButtonItem]];
            // If the top view controller of the navigation controller is current vc, the close item is ignored.
            if (self.navigationController.topViewController != self){
                [leftBarButtonItems addObject:self.navigationCloseBarButtonItem];
            }
            [self.navigationItem setLeftBarButtonItems:leftBarButtonItems animated:NO];
        } else {
            [self.navigationItem setLeftBarButtonItems:@[self.navigationBackBarButtonItem, self.navigationCloseBarButtonItem] animated:NO];
        }
    } else {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        [self.navigationItem setLeftBarButtonItems:@[self.navigationBackBarButtonItem] animated:NO];
    }
}
#pragma mark -- 进度条
- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.frame = CGRectMake(0, 0, self.detailWebView.frame.size.width, 2);
        _progressView.trackTintColor = [UIColor clearColor];
        _progressView.progressTintColor = HEXCOLOR(0x0390f9);
        [_progressView setProgress:0.1 animated:YES];
    }
    return _progressView;
}
#pragma mark -- JS调用OC
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
    
    if ([message.name isEqualToString:@"方法名"]) {
        //传递的参数
       NSString *messageStr = [NSString stringWithFormat:@"%@",message.body];
    }
}
#pragma mark ---  在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL * url = navigationAction.request.URL;
    if ([url.absoluteString containsString:@"zbxapp://h5?jump=customerService"]) {
        if (HYIsEmpty([ZBXSingleData shareInstance].userInfo.token)) {
            FTBaseNavigationViewController *nav = [[FTBaseNavigationViewController alloc]initWithRootViewController:[ZBXLoginViewController new]];
            [self presentViewController:nav animated:YES completion:nil];
            
        }else{
            [[LoginHuanXin new] loginHuanxin:[HYObjectHelper  fetchCurrentVC]];
            
        }
        decisionHandler(WKNavigationActionPolicyCancel);
        
    }else if ([url.absoluteString containsString:@"zbxapp://h5?jump=login"]){
        FTBaseNavigationViewController *nav = [[FTBaseNavigationViewController alloc]initWithRootViewController:[ZBXLoginViewController new]];
        [self presentViewController:nav animated:YES completion:nil];
        
        decisionHandler(WKNavigationActionPolicyCancel);
    }else if ([url.absoluteString containsString:@"zbxapp://h5?jump=adviser"]){
        if (HYIsEmpty([ZBXSingleData shareInstance].userInfo.token)) {
            FTBaseNavigationViewController *nav = [[FTBaseNavigationViewController alloc]initWithRootViewController:[ZBXLoginViewController new]];
            [self presentViewController:nav animated:YES completion:nil];
            
        }else{
            WebPagesViewController *vc = [[WebPagesViewController alloc]init];
            vc.webURL = [NSString stringWithFormat:@"%@#/customizedBuy",webH5URL];
            vc.title = @"定制方案";
            [self.navigationController pushViewController:vc animated:YES];
        }
        decisionHandler(WKNavigationActionPolicyCancel);
    }else if ([url.absoluteString containsString:@"zbxapp://h5?jump=myOrder"]){
        //       [self.navigationController pushViewController:[MyPolicyBaseViewController suspendCenterPageVC] animated:YES];
        //        decisionHandler(WKNavigationActionPolicyCancel);
    }else if ([url.absoluteString containsString:@"zbxapp://h5?jump=policyDetails"]){
        if ([_detailWebView.URL.absoluteString containsString:@"="]) {
            NSArray *array = [_detailWebView.URL.absoluteString componentsSeparatedByString:@"="];
            if (array.count == 2) {
                [self.navigationController pushViewController:[MyPolicyBaseViewController suspendCenterPageVC] animated:YES];
            }
        }
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

- (WKWebView *)detailWebView {
    if (!_detailWebView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        WKPreferences *preferences = [WKPreferences new];
        config.preferences = preferences;
        preferences.javaScriptEnabled = YES;
        //设置监听setTitleVisible
        WKUserContentController* userContentController = WKUserContentController.new;
        config.userContentController = userContentController;
        [userContentController addScriptMessageHandler:self name:@"setTitleVisible"];
        _detailWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        _detailWebView.allowsBackForwardNavigationGestures = YES;
        _detailWebView.backgroundColor = [UIColor clearColor];
        _detailWebView.scrollView.backgroundColor = [UIColor clearColor];
        _detailWebView.translatesAutoresizingMaskIntoConstraints = NO;
        _detailWebView.UIDelegate = self;
        _detailWebView.navigationDelegate = self;
        [_detailWebView addObserver:self forKeyPath:@"scrollView.contentOffset" options:NSKeyValueObservingOptionNew context:NULL];
        [_detailWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        [_detailWebView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _detailWebView;
}
- (instancetype)initWithAddress:(NSString *)urlString {
    
    self = [super init];
    if (self) {
        NSURL *url = [[NSURL alloc] initWithString:urlString];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [self.detailWebView loadRequest:request];
    }
    return self;
}
- (void)showLoadingView{
    NSLog(@"%@-%@",[self class],NSStringFromSelector(_cmd));
    if (_lodingView) {
        return;
    }
    [self.loadingBackView addSubview:self.lodingView];
    [self.view addSubview:self.loadingBackView];
    [self.lodingView startAnimating];
}
- (void)endLoadingView{
    NSLog(@"%@-%@",[self class],NSStringFromSelector(_cmd));
    [_lodingView stopAnimating];
    [_loadingBackView removeFromSuperview];
    _lodingView = nil;
}
-(UIImageView *)lodingView{
    if (!_lodingView) {
        _lodingView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 105*kWidthScale, 105*kHeightScale)];
        _lodingView.center = self.loadingBackView.center;
        _lodingView.animationImages = [LoginHuanXin getGifImages:@"loading" size: CGSizeMake(100, 100)];
        _lodingView.animationDuration = 1.5;
    }
    return _lodingView;
}

- (UIView *)loadingBackView{
    if(!_loadingBackView){
        _loadingBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64)];
        _loadingBackView.backgroundColor = [UIColor whiteColor];
    }
    return _loadingBackView;
}

@end

相关文章

网友评论

      本文标题:iOS 搭建WKWebView框架

      本文链接:https://www.haomeiwen.com/subject/bbterctx.html