WKWebView 拦截URL 为每个请求添加Token

#import "LKSHealthReportViewController.h"
#import 

@interface LKSHealthReportViewController ()
/** <#注释#> */
@property(nonatomic, strong) WKWebView *webView;
/** <#注释#> */
@property(nonatomic, strong) UIView *mainView;
/** 进度条 */
@property(nonatomic, strong) UIProgressView *progressView;
/** 加载失败时候显示界面 */
@property(nonatomic, strong) HWNoDataView *noDataView;
/** 主页URL */
@property(nonatomic, strong) NSURL *url;
/** 请求 */
@property(nonatomic, strong) NSMutableURLRequest *request;
/** 保存当前请求的URL */
@property(nonatomic, strong) NSURL *currentUrl;
@end

@implementation LKSHealthReportViewController

- (HWNoDataView *)noDataView {
    if (!_noDataView) {
        __weak typeof(self) weakSelf = self;
        _noDataView = [HWNoDataView showNoDataViewWithView:self.view title:@"网络不给力,请点击重试"];
        _noDataView.actionBlcok = ^(){
            HWLog(@"点击了屏幕");
            [weakSelf.request setValue:[KUserNamePassWord getAccess_token] forHTTPHeaderField:@"token"];
            [weakSelf.webView loadRequest:weakSelf.request];
        };
    }
    return _noDataView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KHealth,[KUserNamePassWord getDeviceIdStr]]];
    self.request = [NSMutableURLRequest requestWithURL:self.url];
    [HWTools setVCTitleWithName:@"健康报告" VC:self];
    [HWTools setBGColorWithViewController:self];
    [self addMainView];
    [self creatWebView];
}
#pragma mark - 添加进度条
- (void)addMainView {
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HWScreenW, HWScreenH)];
    mainView.backgroundColor = [UIColor clearColor];
    _mainView = mainView;
    [self.view addSubview:mainView];
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, HWScreenW, 1)];
    progressView.progress = 0;
    _progressView = progressView;
    [self.view addSubview:progressView];
}
- (void)creatWebView {
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, HWScreenW, HWScreenH)];
    _webView.backgroundColor = [UIColor whiteColor];
    [self.request setValue:[KUserNamePassWord getAccess_token] forHTTPHeaderField:@"token"];
    _webView.navigationDelegate = self;
    _webView.scrollView.bounces = NO;
    //    _webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(40, 0, 0, 0);
    [_webView loadRequest:self.request];
    [self.mainView addSubview:_webView];
    
    // 添加观察者
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL]; // 进度
}

#pragma mark - WKNavigationDelegate
#pragma mark - 截取当前加载的URL 为每一个请求添加token
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *URL = navigationAction.request.URL;
    HWLog(@"%@", URL);
    if (![[NSString stringWithFormat:@"%@",URL] isEqualToString:[NSString stringWithFormat:@"%@",self.url]]) { // 不是主页 加载
        if (![[NSString stringWithFormat:@"%@",URL] isEqualToString:[NSString stringWithFormat:@"%@",self.currentUrl]]) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
            [request setValue:[KUserNamePassWord getAccess_token] forHTTPHeaderField:@"token"];
            [webView loadRequest:request];
            self.currentUrl = URL;
            decisionHandler(WKNavigationActionPolicyCancel); // 必须实现 取消加载 不然会加载2遍
            return;
        } else {
            self.currentUrl = URL;
            decisionHandler(WKNavigationActionPolicyAllow); // 必须实现 加载
            return;
        }
    } else {
        self.currentUrl = URL;
        decisionHandler(WKNavigationActionPolicyAllow); // 必须实现 加载
        return;
    }
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    self.noDataView.alpha = 0;
}
// 页面加载完毕时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    self.noDataView.alpha = 0;
}
#pragma mark - 监听加载进度
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == _webView) {
            [self.progressView setAlpha:1.0f];
            [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
            if(self.webView.estimatedProgress >= 1.0f) {
                [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    [self.progressView setAlpha:0.0f];
                } completion:^(BOOL finished) {
                    [self.progressView setProgress:0.0f animated:NO];
                }];
            }
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
// 当对象即将销毁的时候调用
- (void)dealloc {
    HWLog(@"webView释放");
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
@end

你可能感兴趣的:(WKWebView 拦截URL 为每个请求添加Token)