Using Google Analytics with Swift on iOS

2019-04-03 18:22发布

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!

2条回答
The star\"
2楼-- · 2019-04-03 19:01

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)
查看更多
叛逆
3楼-- · 2019-04-03 19:01

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

查看更多
登录 后发表回答