Code, Code, Revolution!
I’ve been lazy recently, I know…. But I’e finally gotten around to fix some bugs and added some minor things to “Mitt Saldo” making it ready for version 1.1. A bug was reported that Handelsbanken didn’t work properly on the iPad which was weird because the iPhone works well and it’s the same code. It turns out that UIWebView passes the User-Agent value differently on the iPad from the iPhone.
Handelsbanken keeps track of user-agent values and if they change between requests the authenticated session will terminate. That’s why I wrote about how to extract the user-agent string from UIWebView earlier. In “Mitt Saldo” i make authentication requests using ASIHttpRequest and for the authentication to work in a browser I need to use the same user-agent in UIWebView and for ASIHttpRequest. This is all well, it works perfectly! The weirdness however is the user-agent string for a UIWebView on the iPad. This is the Safari user-agent string on the iPad (actual device) with iOS 4.2:
This is what UIWebView reports on the iPad:
iPad doesn’t report the same user-agent for UIWebView as the Safari app does! iPhone does report the very same user-agent in both Safari and UIWebView! Strange! There’s no reason for UIWebView to behave differently on the iPad than on the iPhone!? Why is this a problem though? Well, some sites, like Handelsbanken, adapt the page based on the user-agent string. If you use the Safari app you get a beautiful iPhone adapted page, if you use UIWebView you get a generic crap version because the user agent is not correct.
I found the solution here, kudos to Alexander Clauss, and it’s called “Method Swizzling”. Because UIWebView is written using Objective-C as well and Objective-C sports functionality to modify classes, methods etc at runtime it’s possible to change the method for settings HTTPHeaders on a NSMutableURLRequest. Check out Alexanders blog post for a more in depth post about it. I’ve attached a sample project below if you want a complete easy to test package.
Download the sample project for changing UIWebView user-agent.
With this blog I try to provide useful tips and solutions for programming .NET, Objective-C and more. My name is Björn Sållarp, and I love writing code.
It's now available on AppStore. It's free and open source. Read more about the app here: Swedish / English
Josh
December 23rd, 2011 at 6:08 am
Downloaded your sample code. Doesn’t compile.
Paul Lopez
February 6th, 2012 at 9:14 am
I came across this article and “method swizzling”, but have read reports that apple will reject apps with swizzling. I found this article that allows you to set the user agent WITHOUT swizzling and is only 4 lines of code:
http://www.mphweb.com/en/blog/easily-set-user-agent-uiwebview