iOS Tip: Force UIWebView to Display Mobile Sites on iPad
So this is actually a very odd tip with a very specific use case. When you embed a UIWebView into your application and feed it static content it will simply render what you tell it to. An issue may arise when you actually have to embed dynamic web content into your application. Hopefully this is a rare case and you are building native apps with Xamarin and C#, but there is one specific case where you have to use a WebView…oAuth. Yes, oAuth! You can’t get around it unless you have your own special oAuth protocol. If you need to tap into facebook, twitter, meetup.com, office, etc you are going to have to present a webview and follow the standard oAuth process. Luckily if you are building your apps with Xamarin then you can use Xamarin.Auth for both iOS and Android, which handles the heavy lifting.
Why force a mobile site in UIWebView?
When using oAuth you are simply directing your user to a web page that has a login screen. Most oAuth login pages have a mobile view, which gives your users a nice experience, but what happens on an iPad? Well, let’s take a look at meetup.com’s oAuth page:
So…. this doesn’t look so great on the iPad and this is because the meetup.com’s oAuth page has decided to show the full website login page instead of the mobile optimized for the iPad. This makes some sense because the iPad is so large and it could handle the full site with it’s larger surface. To me this isn’t a great experience and can even break the oAuth flow to and from mobile pages. So we can fix it!
The UserAgent Fix!
Our good friend User-Agent comes to the rescue. User agent is an http header that helps with content negotiation from a device to a website. In this case the iPad is telling the meetup.com website that it is an iPad and has a large screen. The work around is to simply spoof the UserAgent header that the iPad is sending from our application. Simply add 2 lines of code into your ApplicationDelegate’s FinishedLaunching method:
Now whenever the iPad sends request to a website, the website will think it is an iPhone. I simply grabbed this user agent from whatsmyuseragent.com so if you want to use a different one go for it! Here is our new oAuth page: