WKWebView保持header

作者: sttech | 来源:发表于2017-06-27 15:57 被阅读0次

    iOS 在使用WKWebView的时候一般会在请求里面添加请求头,但是当进入到二级页面的时候就会发现请求头丢掉了,本人找了一个比较笨笨的办法维持住请求头

    • 注意 appNavigationUrl 是请求头的key
    初始化wkwebView的时候设置上header 
     WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
        WKCookiesManager * cookieManager = [WKCookiesManager shareCookies];
        config.processPool = cookieManager.processPool;
        WKPreferences * prefer = [[WKPreferences alloc] init];
        prefer.javaScriptEnabled = YES;
        prefer.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = prefer;
        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:config];
        self.webView.allowsBackForwardNavigationGestures = YES;
        [self.view addSubview:self.webView];
        self.webView.UIDelegate = self;
        self.webView.navigationDelegate = self;
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:timeOutTime];
        [request addValue:_fatherUrl forHTTPHeaderField:@"appNavigationUrl"];
        [self.webView loadRequest:request];
    
    -(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
    开始加载的时候判断是否有header 
    NSURLRequest * request =   navigationAction.request;
      NSMutableURLRequest * mutRequest = [request mutableCopy];
      NSString * urlString = request.URL.absoluteString;
      NSLog(@"====== >>>>url----- %@ request %@",urlString,[request allHTTPHeaderFields]);
      NSDictionary * dictHader = request.allHTTPHeaderFields;
      if (![dictHader objectForKey:@"appNavigation"]) {
          [mutRequest addValue:@"true" forHTTPHeaderField:@"appNavigation"];
          [webView loadRequest:mutRequest];
          decisionHandler(WKNavigationActionPolicyCancel);
      }
    

    相关文章

      网友评论

        本文标题:WKWebView保持header

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