2016-04-26 123 views
6

我已經構建了一個包含WKWebView的應用程序,並且Web視圖加載的網站支持多種語言。如何在WKWebView或其他HTTP頭文件中更改Accept-Language頭文件?如何將自定義HTTP標頭設置爲由WKWebView發出的請求

+0

這是一種http://stackoverflow.com/questions/28984212/how-to-add-httpheader的複本-in-request-global-for-ios-swift/37474812#37474812 看到我對這個問題的回答,它會起作用。我已經測試了Accept-Language,它可以被覆蓋。 –

+2

該解決方案僅適用於初始請求,不適用於子資源。 – mservidio

回答

2

我已經得到它在某種方式工作,但只有得到請求將有自定義標題。正如jbelkins在Gabriel Cartiers的鏈接中回答你的問題所述,你將不得不操縱請求並重新加載它。

我找到了工作GET-請求是這樣的:

(它在xamarin 0> C#,但我想你會明白我的意思)

我創建了一個私有字段

private bool _headerIsSet 

我檢查每一個請求在deligate方法制造時間:

[Foundation.Export("webView:decidePolicyForNavigationAction:decisionHandler:")] 
    public void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler) 
    { 
     var request = navigationAction.Request; 
     // check if the header is set and if not, create a muteable copy of the original request 
     if (!_headerIsSet && request is NSMuteableUrlRequest muteableRequest);    
     { 
      // define your custom header name and value 
      var keys = new object[] {headerKeyString}; 
      var values = new object[] {headerValueString}; 
      var headerDict = NSDictionary.FromObjectsAndKeys(values, keys); 
      // set the headers of the new request to the created dict 
      muteableRequest.Headers = headerDict; 
      _headerIsSet = true; 
      // attempt to load the newly created request 
      webView.LoadRequest(muteableRequest); 
      // abort the old one 
      decisionHandler(WKNavigationActionPolicy.Cancel); 
      // exit this whole method 
      return; 
     } 
     else 
     { 
      _headerIsSet = false;     
      decisionHandler(WKNavigationActionPolicy.Allow); 
     } 
    } 

正如我所說,這隻適用於GET - 請求。不知何故,POST - 請求不包含原始請求(request.Body和request.BodyStream爲null)的正文數據,因此muteableRequest(它是原始請求的可變副本)將不包含原始請求的正文數據。

我希望這可以幫助你或其他人解決同樣的問題。

編輯:您的需求,將「接受語言」爲重點