WKWebView请求添加Token

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler

此代理方法相当于UIWebView的

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

想要在请求的URL中添加头部参数如Token之类的,就是在此方法中拦截URL,添加头部参数
具体方法

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if (_isCareweeLink) {
        BOOL headerIsPresent = [[navigationAction.request allHTTPHeaderFields] objectForKey:@"x-access-ver"]!=nil;
//        LSYLOG(@"%@", [navigationAction.request allHTTPHeaderFields]);
        if(headerIsPresent){
            decisionHandler(WKNavigationActionPolicyAllow);
        }else{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSURL *url = [navigationAction.request URL];
                NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
                [request addValue:_accessVer forHTTPHeaderField:@"x-access-ver"];
                if (LsyUserDefault.x_access_token != nil) {
                    [request addValue:LsyUserDefault.x_access_token forHTTPHeaderField:@"x-access-token"];
                }
                [webView loadRequest:request];
            });
        });
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

你可能感兴趣的:(WKWebView请求添加Token)