UIWebView user-agent weirdness and how to change user-agent value programmatically

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:

Mozilla/5.0 (iPad; U; CPU OS 4_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C134 Safari/6533.18.5

This is what UIWebView reports on the iPad:

Mozilla/5.0 (iPad; U; CPU OS 4_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Mobile/8C134

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.

Enough with the bashing, this is how you set the user-agent for UIWebView

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 sample project

Download the sample project for changing UIWebView user-agent.

3 thoughts on “UIWebView user-agent weirdness and how to change user-agent value programmatically

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>