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

相关文章
相关标签/搜索