DsWebController.m 6.2 KB
//
//  DsWebController.m
//  DreamSleep
//
//  Created by peter on 2022/4/24.
//

#import "DsWebController.h"
#import <WebKit/webKit.h>
#import "DsMaskView.h"
#import "SomeProxy.h"

@interface DsWebController () <WKNavigationDelegate, WKScriptMessageHandler>
@property (nonatomic, copy)   NSString *naviTitle;
@property (nonatomic, strong) NSURL *linkUrl;
@property (nonatomic, assign) BOOL isShowNavi;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSMutableURLRequest *request;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) ExceptionDefaultView *exceptionView;
@end

@implementation DsWebController

- (instancetype)initWithTitle:(NSString *)title link:(NSString *)link {
    if (self = [super init]) {
        self.naviTitle = title;
        self.isShowNavi = YES;
        self.linkUrl = [NSURL URLWithString:link];
    }
    return self;
}

- (instancetype)initWithLink:(NSString *)link isShowNavi:(BOOL)isShowNavi {
    if (self = [super init]) {
        self.linkUrl = [NSURL URLWithString:link];
        self.isShowNavi = isShowNavi;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = self.naviTitle;
    self.view.dk_backgroundColorPicker = DKColorPickerWithKey(VCViewBG);
    
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
    }];
}

- (void)dealloc {
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"AppModel"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

#pragma mark - 关闭侧滑
- (BOOL)enableInteractivePopGestureRecognizer {
    return NO;
}

#pragma mark - 隐藏导航栏
- (BOOL)isShowNavigationBar {
    return !self.isShowNavi;
}

#pragma mark - H5页面导航栏为默认模式
- (NaviStyle)navigationBarStyle {
    return NaviStyleDefault;
}

#pragma mark - WKWebView的监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        self.progressView.hidden = self.progressView.progress == 1;
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    self.exceptionView.hidden = YES;
    [DsMaskView showMaskWithSuperView:self.view];
    self.webView.hidden = NO;
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    DSLog(@"加载失败:%@", error.userInfo);
    self.exceptionView.hidden = NO;
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"AppModel"]) {
        NSDictionary *bodyDic = message.body;
        int type = [bodyDic[@"type"] intValue];
        DSLog(@"bodyDic:%@", bodyDic);
        if (type == 88) { [self.navigationController popViewControllerAnimated:YES]; }
    }
}

#pragma mark - lazy
- (WKWebView *)webView {
    if (!_webView) {
        // 进行配置控制器
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        // 实例化对象
        configuration.userContentController = [WKUserContentController new];
        // 调用JS方法
        [configuration.userContentController addScriptMessageHandler:[[SomeProxy alloc] initObject:self] name:@"AppModel"];
        
        // 进行偏好设置
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = NO;
        preferences.javaScriptEnabled = YES;
        configuration.preferences = preferences;
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
        _webView.navigationDelegate = self;
        _webView.dk_backgroundColorPicker = DKColorPickerWithKey(VCViewBG);
        _webView.scrollView.dk_backgroundColorPicker = DKColorPickerWithKey(VCViewBG);
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.hidden = YES;
        _webView.scrollView.bounces = NO;
        _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:self.linkUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
        self.request = request;
        [_webView loadRequest:self.request];
    }
    return _webView;
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] init];
        _progressView.progressTintColor = HighlightColor;
        _progressView.dk_trackTintColorPicker = DKColorPickerWithKey(VCViewBG);
    }
    return _progressView;
}

- (ExceptionDefaultView *)exceptionView {
    if (!_exceptionView) {
        WS(weakSelf);
        _exceptionView = [[ExceptionDefaultView alloc] initWithType:ExceptionTypeNet block:^{
            weakSelf.progressView.hidden = NO;
            weakSelf.progressView.progress = 0;
            weakSelf.exceptionView.hidden = YES;
            [weakSelf.webView loadRequest:weakSelf.request];
        } superView:self.view];
    }
    return _exceptionView;
}

@end