简体   繁体   中英

Google Analytics not tracking in Swift

I'm trying to get Google Analytics to run in my Swift project. I'm following this tutorial: https://developers.google.com/analytics/devguides/collection/ios/v3/?ver=swift

It says i'm suppose to include it with #import <Google/Analytics.h> that seems to be objective-c though.. however i'm able to do: import Google

I download the GoogleService-info.plist and the it's target membership to my app.

Then i pasted this code:

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

// Optional: configure GAI options.
var gai = GAI.sharedInstance()
gai.trackUncaughtExceptions = true  // report uncaught exceptions
gai.logger.logLevel = GAILogLevel.Verbose  // remove before app releaseAppDelegate.swift

However i don't see any statistics for my app, is there anything i have done wrong or is additional work needed?

You also need to track an event. I think the above code is only for setting up GA in your app. For example, you can add the following code to one of your view controllers whose screen view you want to track :

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

And also keep in mind, that GA events sometimes take very long to show up on the live tracker in the dashboard.

Hope it helps!

    var configureError: NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    guard let gai = GAI.sharedInstance() else {
        assert(false, "Google Analytics not configured correctly")
    }
    gai.trackUncaughtExceptions = true  // report uncaught exceptions
    gai.logger.logLevel = GAILogLevel.verbose  // remove before app release
    gai.dispatchInterval = 20
    gai.tracker(withTrackingId: "UA-XXXXXXXX-X")

   //Track an event
   let tracker = GAI.sharedInstance().defaultTracker
   let eventTracker: NSObject = GAIDictionaryBuilder.createEvent(
    withCategory: YOUR_CATEGORY_NAME,
    action: YOUR_ACTION_NAME",
    label: YOUR_LABEL_NAME,
    value: nil).build()
   tracker?.send(eventTracker as! [AnyHashable: Any])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM