Google Analytics & Swift

Fuad Kamal July 21, 2015 0
Google Analytics & Swift

I’m working on an iOS app written entirely in Swift that uses the Google Analytics library.  At Google I/O 2015 they announced full support for Swift and even CocoaPods (which doesn’t actually work if any of your other libraries use_frameworks! – but they are working on that and it’s not a trivial fix).  The initial intro documentation from Google has options to show the code sample in either Objective-C or Swift, but all the rest of the documentation still seems to be Objective-C, only.  I was listening to the More Than Just Code podcast tonight and Aaron Vegh was remarking on how going back to Swift code just wasn’t clicking, and he found it easier to just write stuff in Objective-C.  So I thought, hey, until Google updates their docs, why not list some Swift code samples for how to implement various things in Swift.

Here I just want to look at a simple task: Event tracking in Google Analytics.  Yes, this might seem trivial, but when you’re a developer switching back and forth between Objective-C and Swift, sometimes it’s nice if someone points out the syntax, as per Aaron’s comments.

Here’s the Objective-C code (adapted from the Google Docs, link above):

[tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"ui action"
                                                      action:@"button press"
                                                       label:@"do something"
                                                       value:@1988] build]];

And here’s the Swift equivalent:

tracker.send(GAIDictionaryBuilder.createEventWithCategory("ui action", action: "button press", label: "do something", value: 1988).build() as [NSObject : AnyObject])

btw if anyone comes up with, or knows of, a nice plugin for WordPress to color code Swift appropriately, please let me know! 😛

 

Links:

Leave A Response »

You must be logged in to post a comment.