iOS UIWebView 修改user-agent

WebView 沒有提供設置user-agent 的接口,不管是設置要加載的request,仍是在delegate 中設置request,經測試都是無效的。以下:web

方案一:xcode

[objc] view plain copy 在CODE上查看代碼片 派生到個人代碼片
  1. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];  
  2. [request addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];  
  3. [self.webView loadRequest:request];  

無效!!!app


方案二:iphone

[objc] view plain copy 在CODE上查看代碼片 派生到個人代碼片
  1. #pragma mark - webview delegate  
  2.   
  3. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  
  4.     NSMutableURLRequest *req = (NSMutableURLRequest *)request;  
  5.     [req addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];  
  6. }  


無效!!!
測試


個人需求是不光要能更改user-agent,並且要保留WebView 原來的user-agent 信息,也就是說我須要在其上追加信息。在stackOverflow上搜集了多方答案,最終彙總的解決方案以下:ui

在啓動時,好比在AppDelegate 中添加以下代碼:lua

[objc] view plain copy 在CODE上查看代碼片 派生到個人代碼片
  1. //get the original user-agent of webview  
  2. UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];  
  3. NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];  
  4. NSLog(@"old agent :%@", oldAgent);  
  5.   
  6. //add my info to the new agent  
  7. NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"];  
  8. NSLog(@"new agent :%@", newAgent);  
  9.   
  10. //regist the new agent  
  11. NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil nil];  
  12. [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];  


這樣,WebView在請求時的user-agent 就是咱們設置的這個了,若是須要在WebView 使用過程當中再次變動user-agent,則須要再經過這種方式修改user-agent, 而後再從新實例化一個WebView。url


參考:spa

http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk/23654363#23654363.net

相關文章
相關標籤/搜索