1. 程式人生 > >UIWebView載入時新增請求頭

UIWebView載入時新增請求頭

http://codecloud.net/16258.html

http://stackoverflow.com/questions/25539837/how-to-add-customize-http-headers-in-uiwebview-request-my-uiwebview-is-based-on

想要在請求頭加參其實很簡單,只要通過以下程式碼:

[request addValue:"head" forHTTPHeaderField:@"key"];

現在主要問題是要在每次載入都在請求頭加參,於是我在網上搜到這篇文章 UIWebView 設定請求頭,基本上可以解決我的需求。下面分析以下程式碼:

func webView(webView:UIWebView, shouldStartLoadWithRequest request:NSURLRequest, navigationType:UIWebViewNavigationType)->Bool{//先判斷是否含有請求頭,打破死迴圈
      let dic
:Dictionary<String,AnyObject>= request.allHTTPHeaderFields!
      let token
= dic["UserToken"]if(token !=nil){returntrue}
      dispatch_async
(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)){()->Voidin
        dispatch_async
(dispatch_get_main_queue(),{()->Voidin
          let newUrl
= request.URL
          let newRequest
:NSMutableURLRequest=NSMutableURLRequest.init(URL: newUrl!)
          newRequest
.addValue(LoginInfoModel.
sharedInstance.m_auth, forHTTPHeaderField:"UserToken")self.webView.loadRequest(newRequest)})}returnfalse}

如上,在uiwebview的代理方法webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) 中攔截網路請求,先檢驗請求中是否含有引數,有引數即直接通過(這一步十分關鍵,因為攔截的請求如沒有引數,會先在請求頭新增引數,再讓web view重新loadRequest,並且在代理方法中要返回NO,loadRequest會重新走這個代理方法,如果沒有以上檢測通過return YES的話,就會陷入死迴圈,)。另外,之所以要在主執行緒中操作,我覺得是與webview的底層載入有關,webview載入時應該是開了子執行緒,所以重新載入要在主執行緒操作,保證執行緒安全。至於文章中提及這種做法進入有iFrame的的頁面會有bug,由於我們後臺頁面沒有iFrame,因此忽略掉。
另外還搜到另一種做法 NSURLProtocol學習筆記-UIWebView 設定請求頭,這種做法聽說更加完美地避免bug,我需要再驗證下,後續再更新……

結束


Sometimes Cookies are not set even after you assign all http headers. it is better to create mutable request and copy your nsurlrequest and add your custom header to it so that all information from original request is retained in mutable one.

-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{if(check if key not present){NSMutableURLRequest*re =[[NSMutableURLRequest alloc] init];//alloc init      not required
  re =(NSMutableURLRequest*) request.mutableCopy;[re setValue:@"Your Custom Value" forHTTPHeaderField:@"Yout Custom     Header"];[webView loadRequest:re];return NO;}return YES;}