Getting Started Guide for Swift

This guide describes how to create and implement an iOS app in Swift to track screen open and button pressed events with Google Tag Manager (GTM).

1. Create a new project

  1. Open Xcode. create a new project
  2. Click Create a new Xcode project.
  3. Select Single View Application. select single view application
  4. Click Next.
  5. Name your project and choose additional options for it. Your project name and app name will be the same as the product name.
    Enter product name and other options
  6. Click Next.
  7. Select a project location (directory).
  8. Click Create.

2. Install Google Tag Manager dependencies

  1. Quit Xcode.
  2. In a terminal, run the following command to install Cocoapods:
    $ sudo gem install cocoapods
    
  3. Change to your project directory.
  4. Run the following command to create a file named Podfile:
    $ pod init
    
  5. In Podfile, uncomment use_frameworks! and add pod 'GoogleTagManager' to the target:
  6. # Uncomment this line if you're using Swift
    use_frameworks!
    
    target 'GtmSwiftTutorial' do
      pod 'GoogleTagManager'
    end
    
  7. Run the following command to download and install Google Tag Manager (GTM) dependencies to your project:
    $ pod install
    

    This command also creates the work space GtmSwiftTutorial.xcworkspace. From now on, use this work space to develop the GtmSwiftTutorial app.

3. Add a bridging header for Objective-C libraries

To create a bridging header file:

  1. Open Xcode.
  2. Click File > New > File.
  3. Under iOS > Source, select Header File.
  4. Click Next.
  5. Enter the header file name BridgingHeader.h.
    Create bridging header file
  6. Click Create.
  7. Add these import statements to the header file:
    #ifndef BridgingHeader_h
    #define BridgingHeader_h
    
    #import <GoogleTagManager/TAGManager.h>
    #import <GoogleTagManager/TAGContainer.h>
    #import <GoogleTagManager/TAGContainerOpener.h>
    #import <GoogleTagManager/TAGDataLayer.h>
    #import <GoogleTagManager/TAGLogger.h>
    
    #endif /* BridgingHeader_h */
    

To add Objective-C bridging header on build settings:

  1. In Xcode, click your project.
  2. Click Build Settings in the editor area.
    Click Build Settings
  3. Select All and Combined and search for bridging.
    Search bridging
  4. On the right column of the row containing Objective-C Bridging Header, enter BridgingHeader.h.
    Add BridgingHeader.h as the Objective-C Bridging Header

4. Add a default container to your project

Before adding a default container to your project, download a mobile container binary:

  1. Sign in to your Google Tag Manager account.
  2. Select a mobile container.
  3. Click Versions at the menu bar.
  4. Click Actions > Download on the selected container version.
  5. The name of the downloaded file is the container ID, for example, GTM-PT3L9Z.

To add a default container binary to your project:

  1. Open Xcode.
  2. Click the Finder icon on the Dock.
  3. Click the Downoloads folder.
  4. Drag the container binary file in the Downloads folder and drop it to your Xcode project's root folder.
  1. In Xcode, open file AppDelegate.swift.
  2. Have the AppDelegate class extend the TAGContainerOpenerNotifier class:
    import UIKit
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, TAGContainerOpenerNotifier {
      // ...
    }
    

    After you extend the class, you'll get the Type 'AppDelegate' does not conform to protocol 'TAGContainerOpenerNotifier' error. The following step will fix this error.

  3. Add the following function to the bottom of the AppDelegate class definition:
    func containerAvailable(container: TAGContainer!) {
      container.refresh()
    }
    
  4. In the application function, add the following code before the return true statement:
    let GTM = TAGManager.instance()
    GTM.logger.setLogLevel(kTAGLoggerLogLevelVerbose)
    
    TAGContainerOpener.openContainerWithId("GTM-PT3L9Z",  // change the container ID "GTM-PT3L9Z" to yours
        tagManager: GTM, openType: kTAGOpenTypePreferFresh,
        timeout: nil,
        notifier: self)
    

6. Track screen open event

To track a screen open event:

  1. Create a variable to store the tracking ID.
  2. Create a data layer variable named screenName.
  3. Create a GTM tag titled Screen View.
  4. Add screen tracking code.

a. Create a variable to store the tracking ID

  1. Sign in to your Google Tag Manager account.
  2. Select a mobile container.
  3. On the left navigation bar, click Variables.
  4. Under User-Defined Variables, click New.
  5. Click Untitled Variable to enter the variable name Tracking ID.
  6. Choose Constant as the variable type.
  7. Enter the tracking ID (in the form of UA-XXXXXXXX-X, where X is a digit) as the value of the variable.
    Use UA-47605289-5 (to be deleted).
  8. Click Create Variable.

b. Create a data layer variable named screenName

  1. Sign in to your Google Tag Manager account.
  2. Select a mobile container.
  3. On the left navigation bar, click Variables.
  4. Under User-Defined Variables, click New.
  5. Click Untitled Variable to enter the title Screen Name.
  6. Choose Data Layer Variable as the variable type.
  7. Enter screenName as the Data Layer Variable Name.
  8. Click Set Default Value.
  9. Enter the default value unknown screen.
  10. Click Create Variable.

c. Create a GTM tag titled Screen View

  1. Sign in to your Google Tag Manager account.
  2. Select a mobile container.
  3. On the left navigation bar, click Tags.
  4. Click New.
  5. Click Untitled Tag to enter the tag name Screen View.
  6. Choose product Google Analytics.
  7. Select Tracking ID from the list.
  8. Select App View as the Track Type.
  9. Click More settings.
  10. Click Fields to Set.
  11. Click + Add Field.
  12. Select field name screenName and its value Screen Name.
  13. Click Continue.
  14. Under Fire On, select Any Event.
  15. Click Create Tag.

d. Add screen tracking code

  1. Open file ViewController.swift in Xcode.
  2. Define a variable named dataLayer inside the ViewController class:
    var dataLayer: TAGDataLayer = TAGManager.instance().dataLayer
    
  3. In the viewDidLoad() function, push the OpenScreen event to the data layer:
    dataLayer.push(["event": "OpenScreen", "screenName": "Home Screen"])
    

The definition of the ViewController class looks like this:

import UIKit

class ViewController: UIViewController {
  var dataLayer: TAGDataLayer = TAGManager.instance().dataLayer

  override func viewDidLoad() {
    super.viewDidLoad()
    dataLayer.push(["event": "OpenScreen", "screenName": "Home Screen"])
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that cant be recreated
  }
}

7. Track button pressed event

To track a button pressed event:

  1. Create a data layer variable named eventAction.
  2. Create a custom event variable named Event.
  3. Create a GTM tag titled Button Pressed.
  4. Create a button and add code to track that the button is pressed.

a. Create a data layer variable named eventAction

  1. Sign in to your Google Tag Manager account.
  2. Select a mobile container.
  3. On the left navigation bar, click Variables.
  4. Under User-Defined Variables, click New.
  5. Click Untitled Variable to enter the title Event Action.
  6. Choose Data Layer Variable as the variable type.
  7. Enter eventAction as the Data Layer Variable Name.
  8. Click Set Default Value.
  9. Enter the default value unknown event.
  10. Click Create Variable.

b. Create a custom event variable named Event

  1. Sign in to your Google Tag Manager account.
  2. Select a mobile container.
  3. On the left navigation bar, click Variables.
  4. Under User-Defined Variables, click New.
  5. Click Untitled Variable to enter the variable name Event.
  6. Choose Custom Event as the variable type.
  7. Click Create Variable.

c. Create a GTM tag titled Button Pressed

  1. Sign in to your Google Tag Manager account.
  2. Select a mobile container.
  3. On the left navigation bar, click Tags.
  4. Click New.
  5. Click Untitled Tag to enter the tag name Button Pressed.
  6. Choose product Google Analytics.
  7. Select Tracking ID from the list.
  8. Select Event as the Track Type.
  9. Select Event category.
  10. Select Event Action.
  11. Click Continue.
  12. Under Fire On, select Any Event.
  13. Click Create Tag.

d. Create a button and add code to track that the button is pressed

  1. Open your Xcode project.
  2. Open Main.storyboard.
  3. Click the top rightmost button in the Xcode toolbar to open the utility area (right sidebar). Story board and utility area
  4. At the bottom of the utility area,
    blue button to open the object library

    click the Show the Object library button (the blue button):

    Object library popup window
  5. Enter button at the search box.
    button in object library
  6. Drag Button to the storyboard and drop it in the top left corner.
    Drag and drop the button to the storyboard
  7. Click the assistant editor button Assistant editor button in the Xcode toolbar.
  8. While holding down the Ctrl key, drag the button and drop it to the bottom of the ViewController class definition.
    Drag-and-drop the button to the ViewController class definition
  9. In the dialog, select Action connection, enter the function name buttonPressed, and click Connect.
    Create code to handle the button-pressed event

    This adds the following function to the end of the ViewController class definition:

    @IBAction func buttonPressed(sender: AnyObject) {
    }
    

    The function is executed every time the button is pressed.

  10. In the buttonPressed function, add the following code to push the ButtonPressed event to the day layer:
    @IBAction func buttonPressed(sender: AnyObject) {
      dataLayer.push(["event": "ButtonPressed", "eventAction": "Test Event"])
    }
    

8. Build and run your app

In Xcode, click Product > Run. Xcode will build and run the app:

Screenshot of launched app