iOS UIWebView 修改user-agent
来源:互联网 发布:linux时间同步 chrony 编辑:程序博客网 时间:2024/05/19 02:02
WebView 没有提供设置user-agent 的接口,无论是设置要加载的request,还是在delegate 中设置request,经测试都是无效的。如下:
方案一:
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
- [request addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];
- [self.webView loadRequest:request];
方案二:
- #pragma mark - webview delegate
- - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
- NSMutableURLRequest *req = (NSMutableURLRequest *)request;
- [req addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];
- }
无效!!!
我的需求是不光要能更改user-agent,而且要保留WebView 原来的user-agent 信息,也就是说我需要在其上追加信息。在stackOverflow上搜集了多方答案,最终汇总的解决方案如下:
在启动时,比如在AppDelegate 中添加如下代码:
- //get the original user-agent of webview
- UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
- NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
- NSLog(@"old agent :%@", oldAgent);
- //add my info to the new agent
- NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"];
- NSLog(@"new agent :%@", newAgent);
- //regist the new agent
- NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil nil];
- [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
这样,WebView在请求时的user-agent 就是我们设置的这个了,如果需要在WebView 使用过程中再次变更user-agent,则需要再通过这种方式修改user-agent, 然后再重新实例化一个WebView。
参考:
http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk/23654363#23654363
转自:http://blog.csdn.net/majiakun1/article/details/49123023
1 0
- iOS UIWebView 修改user-agent
- iOS UIWebView 修改user-agent
- iOS UIWebView 修改user-agent
- iOS UIWebView 修改user-agent
- iOS UIWebView 修改user-agent
- iOS UIWebView 修改user-agent
- ios不用创建UIWebView快速获取系统标准User-Agent
- android user agent修改
- 修改浏览器User-Agent
- 手动修改user-agent
- firefox 修改 user agent
- 修改浏览器user-agent
- 修改浏览器User-Agent
- 修改浏览器User Agent
- iOS中修改WebView默认的User Agent
- iOS中修改WebView默认的User Agent
- iOS中修改WebView默认的User Agent
- UIwebview 如何改User-Agent,让ipad uiwebview模拟iphone
- 三层之窗体登录
- 视频的分辨率
- 在Windows 7 上安装 Mapnik
- cmd
- 想跳槽?先看什么是好工作
- iOS UIWebView 修改user-agent
- QMainWindow布局和QDialog布局的区别
- Linux系统下以RPM方式安装mysql-5.7.9【5.7版本以后,启动mysqld服务首次登录需要密码,为root生成的随机密码在错误日志文件/var/log/mysqld.log】
- rz sz命令
- [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify uniq
- PAT1042
- webrtc在ubuntu14.04上的下载和编译
- loadView详解
- 大数据项目2:内存受限的大数据预测模型