How To Implement Google Tag Manager Enhanced Ecommerce iOS in Xamarin

In Xamarin which is now Microsoft flagship for mobile development, I was challenged to implement Google Tag Manager SDK for iOS (Found on Xamarin components).

Once I started the implementation of Google Tag Manager, I struggled a lot to get the data to show on Google dashboard. After few days in, I was able to see thru the implementation and come up with a solid solution to implement Google Tag Manager Enhanced Ecommerce on any Xamarin iOS app (This is already in production and live apps).

On a separate note, you can get the whole logic flow for Android experience . First, let’s take a look at how code structure will look like inside our general sender method.

NSMutableArray products = new NSMutableArray ();
            if (LIST != null && LIST.Count > 0) {
                foreach (var b in LIST) {
                    NSDictionary p = new NSDictionary ("name", b.name, "id", b.id,
                        "price", b.total, "category", b.category, "quantity", b.quantity);

                    products.Add (NSObject.FromObject (p));
                }

                NSDictionary actionField = new NSDictionary ("id", "value", "revenue", "value", "tax", "value", "shipping", "value", "coupon","value");
                NSDictionary purchase = new NSDictionary ("purchase", new NSDictionary ("products", NSObject.FromObject(products) , "actionField", NSObject.FromObject(actionField)));

                NSDictionary data = new NSDictionary ("event", "purchase", "ecommerce", NSObject.FromObject(purchase));

                manager.DataLayer.Push (data);
            }

Notice that Google takes an array of products, if your solutions only have one product and not a shopping cart concept then the approach is to make a list of one element by using “NSMutableArray“.

From there the trick is to always create an NSDictionary for each meaningful set of data we want to encapsulate and use “NSObject” helper to cast the previous dictionary to base iOS object type. Above hierarchical structure was done following Google documentation about correct format E-commerce.

Google Tag Manager Enhanced Ecommerce iOS in Xamarin

Now the full solution is even trickier since it was discovered by pain that Google SDK contains some unexpected behavior when we start sending multiple e-commerce events. Kudos to Simo Ahaha for his post sharing with useful tips for iOS GTM; tips that saved me from my misery and now I share with you in Xamarin.

If you only need one on Confirmation/ Thank you page then you should be ok, however, I strongly recommend below implementation to walk on the safe side.

Google SDK always save any given event push on memory queue and decide to send them after some time interval in order to save phone battery and internet bandwidth, this is the key difference when comparing against web implementation using javascript where all events are sent real time.

In order to overcome this pending issue, we will have to make sure that we follow 3 principles: (1) Flush data layer to avoid any data collision, (2) prepare e-commerce event push as above example, (3) force data layer to send event at moment and not when scheduled to do it next time. Only force data layer to send events when necessary, the abusing approach will tax users battery life.

The full solution assumes Google Tag Manager object as the one created on AppDelegate and shared across application and proper configuration for basic tracking which is covered here (set Google Tag Manager with needed events). It will contemplate the main method sending the e-commerce data to google, the method is generic enough to help in other events but chime in if need help to get Add/Remove cart, product view, an impression which are similar but with some modifications.

We will demonstrate how to do purchase and checkout steps events below.

public void SendCheckOutSteps (ObservableCollection details, int step)
{
  NSMutableArray products = new NSMutableArray ();
	if (details != null && details.Count > 0) {
	   foreach (var b in details) {
		NSDictionary p = new NSDictionary ("name", b.name, "id", b.id,
				"price", b.SalePrice, "category", "", "quantity", b.count);

		products.Add (NSObject.FromObject (p));
		}

		NSDictionary actionField = new NSDictionary ("step", step);
		NSDictionary checkout = new NSDictionary ("checkout", new NSDictionary("products",NSObject.FromObject(products), "actionField", NSObject.FromObject(actionField)));

		NSDictionary data = new NSDictionary ("event", "checkout", "ecommerce", NSObject.FromObject(checkout));

		ClearEcommerceDataLayer ();

		manager.DataLayer.Push (data);

		ForceDatalayerDispatch ();
	}
}		

public void SendPurchaseEvent (ObservableCollection details,  double totalPrice, string referenceId, string discountCode)
{
	NSMutableArray products = new NSMutableArray ();
	if (details != null && details.Count > 0) {
		foreach (var b in details) {
		var productPrice = b.SalePrice
		NSDictionary p = new NSDictionary ("name", b.name, "id", b.id,
				"price", productPrice, "category", "", "quantity", b.count);

		products.Add (NSObject.FromObject (p));
		}

		NSDictionary actionField = new NSDictionary ("id", referenceId, "revenue", totalPrice, "tax", "", "shipping", "", "coupon", discountCode ?? "");
		NSDictionary purchase = new NSDictionary ("purchase", new NSDictionary ("products", NSObject.FromObject(products) , "actionField", NSObject.FromObject(actionField)));

		NSDictionary data = new NSDictionary ("event", "purchase", "ecommerce", NSObject.FromObject(purchase));

		ClearEcommerceDataLayer ();

		manager.DataLayer.Push (data);

		ForceDatalayerDispatch ();
	}
}		
public void ForceDatalayerDispatch()
{
  manager.Dispatch ();
}

public void ClearEcommerceDataLayer()
{
  manager.DataLayer.Push (new NSDictionary("ecommerce", NSNull.Null));
}

Follow Google Ecommerce documentation to set proper events in Tag Manager admin, make them match this example naming which at the end was taken directly from Google recommendations. Take into account that forcing the manager to dispatch is up to the OS and SDK to honor it and will consume phone battery then do not abuse from its evil power. Let me know if this post helps you out and any recommendation if needed to add another article with other events. Happy Coding!!

One Response

Leave a Reply