UIButton Event Tracking Google Analytics (Swift)
Swift 3: You should use "[AnyHashable: Any]" instead of [NSObject: AnyObject].
Source: https://developer.apple.com/swift/blog/?id=39
guard let tracker = GAI.sharedInstance().defaultTracker else {return}
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])
For Swift 5.
1.You should add GoogleService-Info.plist file in your project (see Google docs).
2.You should add this property in your Info.plist file:
<key>GoogleAnalytics</key>
<dict>
<key>TRACKING_ID</key>
<string>"put_your_tracking_id_here"</string>
</dict>
3.In AppDelegate class, in the didFinishLaunchingWithOptions method:
// GAI
if let gai = GAI.sharedInstance(),
let gaConfigValues = Bundle.main.infoDictionary?["GoogleAnalytics"] as? [String: String],
let trackingId = gaConfigValues["TRACKING_ID"]
{
gai.logger.logLevel = .error
gai.trackUncaughtExceptions = false
gai.tracker(withTrackingId: trackingId)
} else {
assertionFailure("Google Analytics not configured correctly")
}
4.In your ViewController, in the viewDidLoad metod (for example):
// GAI
let tracker = GAI.sharedInstance().defaultTracker
tracker?.set(kGAIScreenName, value: "Your_mark_name")
let eventTracker: NSObject = GAIDictionaryBuilder.createScreenView().build()
tracker?.send(eventTracker as! [NSObject : AnyObject])
5.After what you should drink your beer ;)
For Swift 3
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIDescription, value: "ScreenViewName")
let eventTracker: NSObject = GAIDictionaryBuilder.createScreenView().build()
tracker.send(eventTracker as! [NSObject : AnyObject])
OR...
let tracker = GAI.sharedInstance().defaultTracker
let eventTracker: NSObject = GAIDictionaryBuilder.createEvent(
withCategory: "SomeCategory",
action: "SomeAction",
label: "SomeLabel",
value: nil).build()
tracker.send(eventTracker as [NSObject : AnyObject]!)
Since Swift 1.2 is released, you have to cast GAIDictionaryBuilder
as [NSObject : AnyObject]
See this post on StackOverflow
Google Analytics not working with Swift 1.2 and Xcode 6.3
There is the solution for your issue
@IBAction func startGame1(sender: AnyObject) {
var tracker = GAI.sharedInstance().defaultTracker
tracker.send(GAIDictionaryBuilder.createEventWithCategory("Game 1", action: "Start Pressed", label: "Start Timer One", value: nil).build() as [NSObject : AnyObject])
}
Hope it helps!