CNLiveWebViewController.m 10.4 KB
//
//  CNLiveWebViewController.m
//  CNLiveMineModule_Example
//
//  Created by CNLive-zxw on 2019/12/7.
//  Copyright © 2019 153993236@qq.com. All rights reserved.
//

#import "CNLiveWebViewController.h"
#import <WebKit/WebKit.h>
#import "CNLiveCategory.h"

@interface CNLiveWebViewController ()<WKUIDelegate, WKNavigationDelegate>
@property (nonatomic, copy) NSString *url;
@property (nonatomic, assign) BOOL isShow;

@property (nonatomic, strong) UIView *navigationBar;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *processView;
@property (nonatomic, weak) UILabel *titleLabel;

@end

@implementation CNLiveWebViewController
static const NSInteger margin = 10;

#pragma mark - 初始化方法
- (instancetype)initWithUrl:(NSString *)url title:(nullable NSString *)title{
    return [self initWithUrl:url title:title isShow:NO];
}

- (instancetype)initWithUrl:(NSString *)url title:(nullable NSString *)title isShow:(BOOL)isShow {
    self = [super init];
    if (self) {
        self.url = url;
        self.title = title;
        self.isShow = isShow;
    }
    return self;
}
- (void)setTitle:(NSString *)title{
    _titleLabel.text = title;
}

#pragma mark - 加载数据
- (void)loadUrl {
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    [self.webView loadRequest:theRequest];
}

#pragma mark - 生命周期
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self createSubViews];
    [self loadUrl];
}

- (void)dealloc {
    [self.webView stopLoading];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    if (!self.title) {
        [self.webView removeObserver:self forKeyPath:@"title"];
    }
    self.webView.UIDelegate = nil;
    self.webView.navigationDelegate = nil;
    self.webView = nil;
    
}

- (void)createSubViews {
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.processView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    if (!self.title) {
        [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    }
    
}


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

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}

// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{

}

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

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error{
    NSLog(@"打印这个error%@",error);
}

// 接收到服务器跳转请求之后调用(重定向)
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}

#pragma mark - 响应方法
//回退goBack
- (void)goBack {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }
    else {
        [self closeClick];
    }
}

//关闭pop
- (void)closeClick {
    if (self.presentingViewController != nil) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == self.webView) {
            [self.processView setAlpha:1.0f];
            [self.processView setProgress:self.webView.estimatedProgress animated:YES];
    
            if(self.webView.estimatedProgress >= 1.0f) {
                
                [UIView animateWithDuration:0.3 delay:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [self.processView setAlpha:0.0f];
                    
                } completion:^(BOOL finished) {
                    [self.processView setProgress:0.0f animated:NO];
                    
                }];
                
            }
            
        }
        else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
        
    }
    else if ([keyPath isEqualToString:@"title"]){
        if (object == self.webView) {
            if (self.webView.title.length != 0) {
                self.title = self.webView.title;

            }
        }
        else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - 懒加载
- (UIView *)navigationBar{
    if(!_navigationBar){
        _navigationBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44+[UIApplication sharedApplication].statusBarFrame.size.height)];
        _navigationBar.backgroundColor = [UIColor clearColor];
        [self.view bringSubviewToFront:_navigationBar];
        
        UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        leftBtn.adjustsImageWhenHighlighted = NO;
        leftBtn.frame = CGRectMake(margin, [UIApplication sharedApplication].statusBarFrame.size.height, 44, 44);
        UIImage *leftImage = [self getImageWithImageName:@"web_black_back" bundleName:@"CNLiveUserAgreementManager" targetClass:[self class]];
        [leftBtn setImage:[leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        [leftBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [_navigationBar addSubview:leftBtn];
        
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        closeBtn.adjustsImageWhenHighlighted = NO;
        closeBtn.frame = CGRectMake(44+margin, [UIApplication sharedApplication].statusBarFrame.size.height, 44, 44);
        UIImage *closeImage = [self getImageWithImageName:@"web_black_close" bundleName:@"CNLiveUserAgreementManager" targetClass:[self class]];
        [closeBtn setImage:[closeImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(closeClick) forControlEvents:UIControlEventTouchUpInside];
        [closeBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        closeBtn.hidden = !self.isShow;
        [_navigationBar addSubview:closeBtn];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(([[UIScreen mainScreen] bounds].size.width - 200)/2.0, [UIApplication sharedApplication].statusBarFrame.size.height, 200, 44)];
        titleLabel.font = [UIFont boldSystemFontOfSize:17];
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.text = self.title;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [_navigationBar addSubview:titleLabel];
        _titleLabel = titleLabel;
 
    }
    return _navigationBar;
}

- (WKWebView *)webView{
    if(!_webView){
        WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc] init];
        configuration.allowsInlineMediaPlayback = YES;
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        configuration.preferences = preferences;
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height+44, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height-([UIApplication sharedApplication].statusBarFrame.size.height+44)) configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.contentMode = UIViewContentModeScaleAspectFit;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.allowsBackForwardNavigationGestures = YES;
        _webView.allowsLinkPreview = NO;
        
    }
    return _webView;
}

- (UIProgressView *)processView{
    if(!_processView){
        _processView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, ([UIApplication sharedApplication].statusBarFrame.size.height+44)+0.5, [[UIScreen mainScreen] bounds].size.width, 1)];
        _processView.progressTintColor = [UIColor colorWithRed:19/255.0 green:204/255.0 blue:12/255.0 alpha:1.0];
        _processView.trackTintColor = [UIColor whiteColor];
    }
    return _processView;
}

@end