原网址:点击打开链接
问题描述
在使用webView加载网页的时候,如果遇到点击网页上的操作之后没有反应的。很多控件(例如:GridView、LinkButton等集合元件)需要透过javascript来触发后端事件的功能均没有办法实现。但是也许你会发现,透过Safari浏览ASP.NET网页是不会有问题的,只有在通过App里内嵌UIWebView控件后,无法出现__doPostback的事件才会遇到。.如:加载的网页是一些试题,试题中的选择题是可以直接选择并自动判断的对错的。但是在应用中,用UIWebView加载出来的网页却不能自动判断对错,这个就可能是由于User Agent不能被识别造成的。这种情况只会出现在iPhone4新的iOS之后。
解决办法
由于UIWebView不支持直接修改User Agent,所以改为透过直接覆写NSMutableURLRequest元件的User-Agent,让每次UIWebView都可以使用修改过的User Agent来发送给指定的Web Server取得正确的JavaScript与CSS。但由于每次都要修改NSMutableURLRequest的User Agent很不方便,透过该< Easily set the User-Agent in a UIWebView | MPHWeb >篇的介绍,它提供直接在init时就让UIWebView取得设定,这样就不需每次都修改啦。
如以下的范例:
1: //设定UserAgent参数,绑定在每次UIWebView的Request中使用
2:
3: NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:
4: @"Mozilla/5.0 (iPhone; U; CPU OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/4.0 Mobile/8C148 Safari/528.16" ,
5: @"UserAgent" , nil];
6: [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
7: [dictionnary release];
User Agent的参数:
Mozilla/5.0 (iPhone; U; CPU OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/4.0 Mobile/8C148 Safari/528.16
References:
‧ ASP.NET 4.0 issue with BrowserCap incorrectly detecting UIWebView (Safari) in iOS (问题的原由)
‧ Programmatically fill in data in a UIWebview
‧ Easily set the User-Agent in a UIWebView | MPHWeb (必读)
‧ iPhone/iPad – Get User-Agent for UIWebView
‧ Change User Agent in UIWebView (iPhone SDK)