Tip 39: Launch campaign tracking in Google Tag Manager for iOS

1. Modifying the app code

To parse the URL, we’ll leverage the setCampaignParametersFromUrl method in the GAIDictionaryBuilder class of the Google Analytics SDK. We won’t use it for anything else except for parsing the URL. So, in your AppDelegate.swift file, locate the overloaded constructor with the handleOpenURL method, or create it yourself:

Let’s just quickly walk through this. urlString is the variable where we’ll store the URL string itself (d’oh). hitParams is what we’ll use to parse the URL, and dataLayer is where we’ll push the information.

The setCampaignParametersFromUrl() method takes a URL string, and parses it for the regular UTM campaign parameters. It stores them in a bunch of constants the GA SDK leverages to pass information between the app and Google Analytics.

Summary

There’s one thing you need to pay heed to. We’re pushing the campaign parameters to dataLayer but we’re not sending an ‘event’ key. The reason for this is that we want the app to send its regular Screen View, using these values only if they’re in the dataLayer when the Screen View is dispatched.

You probably see how this can be a problem. If your app sends a Screen View as soon as the initial view appears, it’s possible this dataLayer.push() happens after the Screen View hit is built, leading to a nasty race condition. The best way to ensure it works is to defer the initial hit to Google Analytics until the handleOpenURL method has completed.

The whole thing is slightly more complex than when using just the GA SDK, as many things seem to be with the Google Tag Manager SDK, but it’s still consistent with leveraging dataLayer for message passing, rather than communicating directly with the endpoint.