简体   繁体   English

在iOS上使用Google Analytics和Swift

[英]Using Google Analytics with Swift on iOS

I'm trying to use GA with a Swift project. 我正在尝试将GA与Swift项目一起使用。

I installed the SDK correctly but I can't send Screen Measurements manually because some objects are not found. 我正确安装了SDK,但我无法手动发送屏幕测量,因为找不到某些对象。

Here's the code given by Google: 以下是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. 我在我的BridingHeader中导入了GAI.h,并在构建文件中添加了框架,这方面没有错误。

Thanks! 谢谢!

OK so I just added GAI.h to my bridging header but didn't add others header files. 好的,所以我只是将GAI.h添加到我的桥接头但没有添加其他头文件。 And thanks DPLusV I also didn't translated correctly Obj-C to Swift. 并且感谢DPLusV我也没有正确地将Obj-C翻译成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 [编辑] 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)

I followed the instructions in 我按照说明进行操作

https://developers.google.com/analytics/devguides/collection/ios/v3/?ver=swift 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 我已经有一个GoogleService-Info.plist文件,我启用了谷歌分析

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. 我将这段代码放在View Controller(s)中,只要它需要它。

Hope this help someone. 希望这能有所帮助。 Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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