Skip to content
generated from brightdigit/EggSeed

Google Analytics Measurement Protocol API for Swift

License

Notifications You must be signed in to change notification settings

brightdigit/GampKit

Repository files navigation

Logo of the project

GampKit

SwiftPM Twitter GitHub GitHub issues Beerpay

GitHub Workflow Status Travis (.com) CircleCI Bitrise

Codecov CodeFactor Grade codebeat badge Code Climate maintainability Code Climate technical debt Code Climate issues

Version License Platform Cocoapods doc percentage Carthage compatible Reviewed by Hound

Using Google Analytics for Tracking Events, Timing, Errors and more

Rather than downloading large amounts of libraries framework in order to understand how your app is used, you can use this library for easy data. The library works directly with Google Analytics using their Measure Protocol API. See all your data right from the Google Analytics dashboard.

Features

Included with this library is the ability to track:

  • Events with Custom Data
  • Timing of various operations
  • Swift Errors and NSExceptions
  • Custom actions such screens and transactions

Reqirements

  • iOS 8.0+ / macOS 10.9+ / tvOS 9.0+ / watchOS 2.0+ / Linux
  • Xcode 10.2+
  • Swift 5+

Installing

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate GampKit into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'GampKit', '~> 0.1.0'

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. GampKit does support its use on supported platforms.

Once you have your Swift package set up, adding GampKit as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/brightdigit/GampKit.git", .upToNextMajor(from: "0.1.0"))
]

Usage

Before moving forward make sure to setup a property under your Google Analytics account. With your new property for your application, you will need your tracking identifier. Typically a tracking identifier has a format of UA-XXXXXXXXX-XX. You will need the tracking identifier as well as the:

  • Application Name
  • Application Version
  • Client Identifier - this should be a ananymous UUID created on application installation and saved to future use on launch

Configuration

In order to begin tracking, you will need to setup a AnalyticsTracker with the configuration of your application using a AnalyticsConfiguration object:

  let tracker = AnalyticsTracker(configuration: AnalyticsConfiguration(
    trackingIdentifier: "UA-XXXXXXXX-XX",
    applicationName: "GampKitDemo",
    applicationVersion: "1.0",
    clientIdentifier: clientIdentifer
  ))

Now that you have setup your AnalyticsTracker, let's being tracking events.

Tracking

There are three types of tracking objects: Events, Timing, and Exceptions.

Events

For tracking events, you can create an AnalyticsEvent with a category and action:

    let event = AnalyticsEvent(category: "category", action: "action")
    tracker.track(event) { result in
      if case let .failure(error) = result {
        debugPrint(error)
      }
    }

You can read more details about events on the Google Analytics Measurement Protocol documentation.

Timing

For tracking timing, you can create an AnalyticsTiming or use AnalyticsTracker.track(time:...) with a category and action:

    let start : Date
    ...
    let timing = start.timeIntervalSinceNow
    tracker.track(time: -timing, withCategory: "jsonLoader", withVariable: "load") { result in
      if case let .failure(error) = result {
        debugPrint(error)
      }
    }

You can read more details about timing on the Google Analytics Measurement Protocol documentation.

Errors and Exceptions

For tracking errors and exceptions, you can use AnalyticsTracker.track(error:...):

    do {
      try doSomething()
    } catch let error {
      tracker.track(error: error, isFatal: false) { result in
        if case let .failure(error) = result {
          debugPrint(error)
        }
      }
    }

You can read more details about events on the Google Analytics Measurement Protocol documentation.

Custom Items

You can also track custom items by implementing AnalyticsTrackable. This requires the implmentation of two methods:

  var hitType: AnalyticsHitType {
    get
  }

  func parameters() -> AnalyticsParameterDictionary

An AnalyticsParameterDictionary is simply a dictionary with keys of type AnalyticsParameterKey.

public typealias AnalyticsParameterDictionary = [AnalyticsParameterKey: Any]

public enum AnalyticsParameterKey: String, CaseIterable {
  case hitType = "t", version = "v", trackingId = "tid",
    userTimingCategory = "utc", userTimingLabel = "utl", timing = "utt", clientId = "cid",
    userTimingVariable = "utv",
    applicationName = "an", applicationVersion = "av", eventAction = "ea",
    eventCategory = "ec", eventLabel = "el", eventValue = "ev",
    userLanguage = "ul", operatingSystemVersion = "cd1", model = "cd2",
    exceptionDescription = "exd", exceptionFatal = "exf"
}

The rules regarding what are required based on hit type and each parameter is located in the Google Analytics Measurement Protocol Parameter Reference.

Debugging vs. Release

By default, the library will either use the Google Analytics Measurement Protocol API url for validation purposes or the actual url depending on whether the build is DEBUG or RELEASE. When using the validation server, no items will be actually be tracked only validated. You can override this in one of two ways:

  1. Supply a custom URL for the AnalyticsSessionManager
  let tracker = AnalyticsTracker(configuration: AnalyticsConfiguration(
    trackingIdentifier: "UA-XXXXXXXX-XX",
    applicationName: "GampKitDemo",
    applicationVersion: "1.0",
    clientIdentifier: clientIdentifer
  ), sessionManager: AnalyticsURLSession(url : url))
  1. Use the debug mode flag for using the validation server
  let tracker = AnalyticsTracker(configuration: AnalyticsConfiguration(
    trackingIdentifier: "UA-XXXXXXXX-XX",
    applicationName: "GampKitDemo",
    applicationVersion: "1.0",
    clientIdentifier: clientIdentifer
  ), debugMode: false)

Links

License

GampKit is released under the MIT license. See LICENSE for details.