Implement Google Analytics in ios swift

寵の児 提交于 2019-12-02 21:02:31

There are two options for implementation with Google Analytics using CocoaPods.

  1. pod 'Google/Analytics'
  2. pod 'GoogleAnalytics'

There are pros and cons between them.

pod 'Google/Analytics'

  • need google configuration file(GoogleService-Info.plist)
  • simple bridging header file. Just add #import <Google/Analytics.h> in bridging header file.
  • add import Googlein every file you want to implement google analytics.

pod 'GoogleAnalytics'

  • no google configuration file(GoogleService-Info.plist)
  • more complex bridging header file.

I prefer to use pod 'GoogleAnalytics' but I'll explain how to solve this issue using pod 'Google/Analytics' because the google official site recommends pod 'Google/Analytics'.

  1. bridging header

You just need one line of code for google analytics.

#import <Google/Analytics.h>

Don't forget to set target-build setting for Objective-C-Bridging-Header. You have to provide correct path to enable Objective-C-Bridging-Header.

Set Target-Build Setting-Objective-C-Bridging-Header $(SRCROOT)/$(PRODUCT_NAME)/projectName_Bridging_Header.h

  1. AppDelegate.swift
import Google

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
-> Bool { self.setupGoogleAnalytics()
..
     self.setupGoogleAnalytics()
..
 }

func setupGoogleAnalytics() {

    // Configure tracker from GoogleService-Info.plist.
    let configureError:NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    let gai = GAI.sharedInstance()
    gai.trackUncaughtExceptions = true  // report uncaught exceptions
    gai.logger.logLevel = GAILogLevel.Verbose  // remove before app release
}
  1. SomeViewController.swift
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)

    if let default_tracker = GAI.sharedInstance().defaultTracker {
        #if DEBUG

            print("default tracker")

        #endif
    }

    //        let tracker = GAI.sharedInstance().defaultTracker
    let tracker = GAI.sharedInstance().trackerWithTrackingId("tracking_ID")
    tracker.set(kGAIScreenName, value: screenName)
    let builder = GAIDictionaryBuilder.createScreenView()
    tracker.send(builder.build() as [NSObject : AnyObject])

}

Why do I use trackerWithTrackingId instead of defaultTracker property? You could got an error if you use defaultTracker :

fatal error: unexpectedly found nil while unwrapping an Optional value

defaultTracker property's initial value is nil, but it will be set after trackerWithTrackingId method is called. But it doesn't work perfectly sometimes. To avoid this issue, I recommend that use trackerWithTrackingId method directly.

I make the sample project using pod 'GoogleAnalytics'. You can get an idea from it. Good luck.

Test Env

GoogleAnalytics 3.14

Xcode 7.2.1

In Podfile

pod 'Google/Analytics'

In YourFantasticProjectName-Bridging-Header.h

#import "Google/Analytics.h"

You don't need this

GGLContext.sharedInstance().configureWithError(&configureError)

You need to have a proper tracker

let gai = GAI.sharedInstance()
let tracker = gai.tracker(withTrackingId: "UA-12345678-1")

In order for live view to work in GA dashboard, you must track screen using GAIDictionaryBuilder and correct key kGAIScreenName

tracker.set(kGAIScreenName, value: "this is my screen")
let event = GAIDictionaryBuilder.createScreenView()
tracker?.send(event!.build() as! [NSObject: Any])

In the same vein, to track events, you need to use GAIDictionaryBuilder as it will create dictionary with correct GA keys, and GA likes correct keys

let event = GAIDictionaryBuilder.createEvent(withCategory: "category", action: "action", label: "level", value: NSNumber(value: 120))
tracker?.send(event!.build() as! [NSObject: Any])

It seems to work in the simulator too

I faced the same problem. I could not import the "Google/Analytics.h" header as Xcode generate error. Because "Google/Analytics.h" header is not available in the 'GoogleAnalytics sdk' as mentioned in Google's Official page.

So, i just used following line

#import "GAI.h"

Hope it will work just fine. Environment Xcode: 8.2 iOS :10.2

For swift 3:

    var configureError:NSError? = nil
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")
    let gai = GAI.sharedInstance()
    gai?.trackUncaughtExceptions = true
    gai?.logger.logLevel = GAILogLevel.verbose

I think it's better to send error to crashlytics, but continue executing an app:

func configureGoogleAnalytics() {
    var configureError: NSError? = nil
    GGLContext.sharedInstance().configureWithError(&configureError)
    if configureError != nil {
        Crashlytics.sharedInstance().recordError(configureError!)
    }
}

Also check this answer for newest way to add analytics.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!