Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Google Analytics with Swift on iOS

Tags:

I'm trying to use GA with a Swift project.

I installed the SDK correctly but I can't send Screen Measurements manually because some objects are not found.

Here's the code given by Google:

// May return nil if a tracker has not already been initialized with a
// property ID.
id tracker = [[GAI sharedInstance] defaultTracker];

// This screen name value will remain set on the tracker and sent with
// hits until it is set to a new value or to nil.
[tracker set:kGAIScreenName
   value:@"Home Screen"];

// New SDK versions
[tracker send:[[GAIDictionaryBuilder createScreenView] build]];

Here's my code:

let tracker = GAI.sharedInstance()
tracker.setValue(kGai, forKey: "/index")
tracker.send(GAIDictionaryBuilder.createScreenView().build)

And here's the errors I get:

Use of unresolved identifier 'kGAIScreenName'
Use of unresolved identifier 'GAIDictionaryBuilder'

I imported GAI.h in my BridingHeader and added frameworks to the build file, no errors on this side.

Thanks!

like image 246
Skoua Avatar asked Nov 07 '14 10:11

Skoua


2 Answers

OK so I just added GAI.h to my bridging header but didn't add others header files. And thanks DPLusV I also didn't translated correctly Obj-C to Swift.

Here is my final code which works:

let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: "/index")
tracker.send(GAIDictionaryBuilder.createScreenView().build())

[EDIT] SWIFT 3

let tracker = GAI.sharedInstance().defaultTracker
tracker?.set(kGAIScreenName, value: "/index")
let build = (GAIDictionaryBuilder.createScreenView().build() as NSDictionary) as! [AnyHashable: Any]
tracker?.send(build)
like image 65
Skoua Avatar answered Oct 18 '22 15:10

Skoua


I followed the instructions in

https://developers.google.com/analytics/devguides/collection/ios/v3/?ver=swift

up till pod installation

I already had a GoogleService-Info.plist file there I enabled the google analytics

Then I did some hit and trial methods to make it work

And finally I found some thing which worked for me

let googleAnalytics : GAITracker = GAI.sharedInstance().trackerWithTrackingId("UA-XXXXXXXX-X")
GAI.sharedInstance().trackUncaughtExceptions = true
googleAnalytics.set(kGAIScreenName, value: screenName)
let builder = GAIDictionaryBuilder.createScreenView()
googleAnalytics.send(builder.build() as [NSObject : AnyObject])

I put this piece of code in View Controller(s) where ever it was needed.

Hope this help someone. Thanks

like image 43
bably Avatar answered Oct 18 '22 15:10

bably