How to add a custom user agent in the header using a webview and Xamarin Forms

I am writing an app using Xamarin Forms and wanted to control the user agent for my webview. It’s a little hacky way to have the website render differently when it see that it’s my app coming in without having to use session cookies or other crap like that.

It was pretty easy once I found the code, but finding the code was the pain. Well, Add this renderer to your IOS project.

Snippet

using Foundation;
using PrazeMeApp.iOS.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
 
[assembly: ExportRenderer(typeof(WebView), typeof(MyWebViewRenderer))]
namespace PrazeMeApp.iOS.Renderers
{
    public class MyWebViewRenderer : WebViewRenderer
        {
            protected override void OnElementChanged(VisualElementChangedEventArgs e)
            {
            NSDictionary dictionary = NSDictionary.FromObjectAndKey(NSObject.FromObject("myuseragentgoeshere"), NSObject.FromObject("UserAgent"));
            NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary);
            base.OnElementChanged(e);
            }
        }
    }

 

Happy Coding!

Xamarin PCL – How to URL Encode since there is no HttpUtility

Looking for the HTTPUtility class? Ha, you don’t get it. PCL doesn’t have it. Fret not, though, you can still URL Encode.

It’s easy, just in a different spot.

How to URLEncode in Xamarin Forms PCL

var encodedData = System.Net.WebUtility.UrlEncode(stuffToEncode);

Now you know, and now hopefully I will remember!

Happy coding!