UIWebView iOS5更改用户代理

如何更改iOS 5中的UIWebView的用户代理?

到目前为止我所做的:使用委托callback,截取NSURLRequest,创build一个新的url请求,并将其设置为用户代理,然后下载数据,并用“loadData:MIMEType:”重新加载UIWebView。 “。

问题:这会导致无限recursion,在那里我加载数据,调用委托返回,哪个实习生调用委托….

这是委托方法:

- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { dispatch_async(kBgQueue, ^{ NSURLResponse *response = nil; NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[request URL]]; NSDictionary *headers = [NSDictionary dictionaryWithObject: @"custom_test_agent" forKey:@"User-Agent"]; [newRequest setAllHTTPHeaderFields:headers]; [self setCurrentReqest:newRequest]; NSData *data = [NSURLConnection sendSynchronousRequest:newRequest returningResponse:&response error:nil]; dispatch_sync(dispatch_get_main_queue(), ^{ [webView loadData:data MIMEType:[response MIMEType] textEncodingName:[response textEncodingName] baseURL:[request URL]]; }); }); return YES; } 

当您的应用程序启动时,通过运行以下代码更改“UserAgent”默认值:

 NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Your user agent", @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary]; 

编辑:我用这很大的成功,但要添加额外的细节。 要获得用户代理,您可以启用“开发人员”菜单,设置用户代理,然后连接到该网站,为您打印出来: WhatsMyAgent 。 同样,您可以使用任何types的移动设备进行连接,也可以使用这种方式。 顺便说一句,这仍然在iOS7 +中工作得很好

Swift中使用这个来设置UserAgent

 func setUserAgent(){ var userAgent = NSDictionary(objectsAndKeys: "YourUserAgentName","UserAgent") NSUserDefaults.standardUserDefaults().registerDefaults(userAgent as [NSObject : AnyObject]) } 

用这个来testing,

 println(WebView.stringByEvaluatingJavaScriptFromString("navigator.userAgent")); 

当你发送消息[aWebView loadData:MIMEType:textEncodingName:baseURL:]

那么一个aWebView shouldStartLoadWithRequest:将被再次调用,然后再次 – 这就是为什么你得到一个无限recursion

你应该限制调用你的dispatch_async()块,例如使用一些传统的URL:

 - (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if ([[[request URL] absoluteString] isEqualToString:@"http://yourdomain.com/?local=true"]) { return YES; } ... dispatch_async(... [aWebView loadData:data MIMEType:[response MIMEType] textEncodingName:[response textEncodingName] baseURL:[NSURL URLWithString:@"http://yourdomain.com/?local=true"]]; ); return NO; }