在ios swift中实施Google Analytics

时间:2022-02-25 15:16:39

I am following the Analytics for iOS (developers.google.com/analytics/devguides/collection/ios/v3/?ver=swift) guide and I've got errors in my Swift code Project that I can't fix. I am working with XCode 6.4, Swift and the iOS Deployment Target 8.1.

我正在关注iOS版Analytics(developers.google.com/analytics/devguides/collection/ios/v3/?ver=swift)指南,我在Swift代码项目中遇到了无法修复的错误。我正在使用XCode 6.4,Swift和iOS部署目标8.1。

Step 1

步骤1

First I installed a Google SDK using CocoaPods. This is the console result after running pod install command:

首先,我使用CocoaPods安装了Google SDK。这是运行pod install命令后的控制台结果:

Updating local specs repositories

CocoaPods 1.0.0.beta.2 is available.
To update use: `gem install cocoapods --pre`
[!] This is a test version we'd love you to try.

For more information see http://blog.cocoapods.org
and the CHANGELOG for this version http://git.io/BaH8pQ.

Analyzing dependencies
Downloading dependencies
Using Google (1.0.7)
Using GoogleAnalytics (3.14.0)
Using GoogleNetworkingUtilities (1.0.0)
Using GoogleSymbolUtilities (1.0.3)
Using GoogleUtilities (1.1.0)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There is 1 dependency from the
Podfile and 5 total pods installed.

Step 2

第2步

Then opened, as said in the guide, my app's Project .xcworkspace file.

然后打开,如指南中所述,我的应用程序的Project .xcworkspace文件。

My Podfile looks like this:

我的Podfile看起来像这样:

# Uncomment this line to define a global platform for your project
# platform :ios, '8.0'
# Uncomment this line if you're using Swift
# use_frameworks!

target 'XXXXXX' do

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.1'
pod 'Google/Analytics', '~> 1.0.0'

end

target 'XXXXXXTests' do

pod 'Google/Analytics', '~> 1.0.0'

end

Where XXXXXX is my Project's name.

XXXXXX是我项目的名称。

Step 3

第3步

I got the configuration file GoogleService-Info.plist and included in my Project adding all the targets (2 targets in my project).

我得到了配置文件GoogleService-Info.plist,并在我的项目中添加了所有目标(我的项目中有2个目标)。

Step 4

步骤4

I created a BridgingHeader by by choosing File > New > File > iOS > Source > Header File. I named it BridgingHeader.h and is in the root of my Project. The content is:

我通过选择File> New> File> iOS> Source> Header File创建了一个BridgingHeader。我将它命名为BridgingHeader.h并且位于我的项目的根目录中。内容是:

#ifndef XXXXX_BridgingHeader_h
#define XXXXX_BridgingHeader_h

#import "Google/Analytics.h"
#import <Google/Analytics.h>
#include "GAI.h"

#import <CoreData/CoreData.h>
#import <SystemConfiguration/SystemConfiguration.h>

#import "Libraries/GoogleAnalytics/GAI.h"
#import "Libraries/GoogleAnalytics/GAIFields.h"
#import "Libraries/GoogleAnalytics/GAILogger.h"
#import "Libraries/GoogleAnalytics/GAITracker.h"
#import "Libraries/GoogleAnalytics/GAIDictionaryBuilder.h"

#endif

Where "XXXXX" is my Project's name.

“XXXXX”是我项目的名称。

Step 5

第5步

Now the problems: I tried to include/import the Google Analytics into my AppDelegate.swift but I can't. This is the error:

现在问题是:我试图将Google Analytics包含/导入我的AppDelegate.swift,但我不能。这是错误:

AppDelegate.swift import Google Analytics

AppDelegate.swift导入Google Analytics

I also tried import "Google/Analytics.h" but another error appears: Expected identifier in import declaration.

我还尝试导入“Google / Analytics.h”,但出现了另一个错误:导入声明中的预期标识符。

  • How can I fix this so XCode doesn't give me errors?
  • 我怎么能解决这个问题,所以XCode不会给我错误?
  • Is the BridgingHeader wrong? Do I have to point at this somehow to recognize its inner headers?
  • BridgingHeader错了吗?我是否必须以某种方式指出它的内部标题?
  • Do I have to configure something else for the Google Analytics that I am missing right now?
  • 我是否必须为我现在缺少的Google Analytics配置其他内容?

Thank you very much.

非常感谢你。

5 个解决方案

#1


29  

There are two options for implementation with Google Analytics using CocoaPods.

使用CocoaPods可以使用Google Analytics实施两种方法。

  1. pod 'Google/Analytics'
  2. pod'Google / Analytics'
  3. pod 'GoogleAnalytics'
  4. pod'GoogleAnalytics'

There are pros and cons between them.

他们之间有利有弊。

pod 'Google/Analytics'

pod'Google / Analytics'

  • need google configuration file(GoogleService-Info.plist)
  • 需要谷歌配置文件(GoogleService-Info.plist)
  • simple bridging header file. Just add #import <Google/Analytics.h> in bridging header file.
  • 简单的桥接头文件。只需在桥接头文件中添加#import 即可。
  • add import Googlein every file you want to implement google analytics.
  • 在每个要实施Google Analytics的文件中添加导入Google。

pod 'GoogleAnalytics'

pod'GoogleAnalytics'

  • no google configuration file(GoogleService-Info.plist)
  • 没有谷歌配置文件(GoogleService-Info.plist)
  • more complex bridging header file.
  • 更复杂的桥接头文件。

I prefer to use pod 'GoogleAnalytics' but I'll explain how to solve this issue using pod 'Google/Analytics' because the google official site recommends pod 'Google/Analytics'.

我更喜欢使用pod'GoogleAnalytics',但我会解释如何使用pod'Google / Analytics'解决此问题,因为谷歌官方网站推荐使用pod'Google / Analytics'。

  1. bridging header
  2. 桥头

You just need one line of code for google analytics.

您只需要一行代码用于Google Analytics。

#import <Google/Analytics.h>

Don't forget to set target-build setting for Objective-C-Bridging-Header. You have to provide correct path to enable Objective-C-Bridging-Header.

不要忘记为Objective-C-Bridging-Header设置目标构建设置。您必须提供正确的路径才能启用Objective-C-Bridging-Header。

Set Target-Build Setting-Objective-C-Bridging-Header $(SRCROOT)/$(PRODUCT_NAME)/projectName_Bridging_Header.h

设置Target-Build Setting-Objective-C-Bridging-Header $(SRCROOT)/ $(PRODUCT_NAME)/projectName_Bridging_Header.h

  1. AppDelegate.swift
  2. AppDelegate.swift
import Google

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
-> Bool { self.setupGoogleAnalytics()
..
     self.setupGoogleAnalytics()
..
 }

func setupGoogleAnalytics() {

    // Configure tracker from GoogleService-Info.plist.
    let configureError:NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    let gai = GAI.sharedInstance()
    gai.trackUncaughtExceptions = true  // report uncaught exceptions
    gai.logger.logLevel = GAILogLevel.Verbose  // remove before app release
}
  1. SomeViewController.swift
  2. SomeViewController.swift
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)

    if let default_tracker = GAI.sharedInstance().defaultTracker {
        #if DEBUG

            print("default tracker")

        #endif
    }

    //        let tracker = GAI.sharedInstance().defaultTracker
    let tracker = GAI.sharedInstance().trackerWithTrackingId("tracking_ID")
    tracker.set(kGAIScreenName, value: screenName)
    let builder = GAIDictionaryBuilder.createScreenView()
    tracker.send(builder.build() as [NSObject : AnyObject])

}

Why do I use trackerWithTrackingId instead of defaultTracker property? You could got an error if you use defaultTracker :

为什么我使用trackerWithTrackingId而不是defaultTracker属性?如果使用defaultTracker,则可能会出错:

fatal error: unexpectedly found nil while unwrapping an Optional value

致命错误:在展开Optional值时意外发现nil

defaultTracker property's initial value is nil, but it will be set after trackerWithTrackingId method is called. But it doesn't work perfectly sometimes. To avoid this issue, I recommend that use trackerWithTrackingId method directly.

defaultTracker属性的初始值为nil,但它将在trackerWithTrackingId方法被调用后设置。但它有时并不完美。为避免此问题,我建议直接使用trackerWithTrackingId方法。

I make the sample project using pod 'GoogleAnalytics'. You can get an idea from it. Good luck.

我使用pod'GoogleAnalytics'制作示例项目。你可以从中得到一个想法。祝你好运。

Test Env

测试环境

GoogleAnalytics 3.14

GoogleAnalytics 3.14

Xcode 7.2.1

Xcode 7.2.1

#2


8  

In Podfile

在Podfile中

pod 'Google/Analytics'

In YourFantasticProjectName-Bridging-Header.h

在YourFantasticProjectName-Bridging-Header.h中

#import "Google/Analytics.h"

You don't need this

你不需要这个

GGLContext.sharedInstance().configureWithError(&configureError)

You need to have a proper tracker

你需要一个合适的跟踪器

let gai = GAI.sharedInstance()
let tracker = gai.tracker(withTrackingId: "UA-12345678-1")

In order for live view to work in GA dashboard, you must track screen using GAIDictionaryBuilder and correct key kGAIScreenName

要使实时视图在GA仪表板中工作,您必须使用GAIDictionaryBuilder跟踪屏幕并更正密钥kGAIScreenName

tracker.set(kGAIScreenName, value: "this is my screen")
let event = GAIDictionaryBuilder.createScreenView()
tracker?.send(event!.build() as! [NSObject: Any])

In the same vein, to track events, you need to use GAIDictionaryBuilder as it will create dictionary with correct GA keys, and GA likes correct keys

同样,要跟踪事件,您需要使用GAIDictionaryBuilder,因为它将使用正确的GA键创建字典,GA喜欢正确的键

let event = GAIDictionaryBuilder.createEvent(withCategory: "category", action: "action", label: "level", value: NSNumber(value: 120))
tracker?.send(event!.build() as! [NSObject: Any])

It seems to work in the simulator too

它似乎也在模拟器中工作

#3


7  

I faced the same problem. I could not import the "Google/Analytics.h" header as Xcode generate error. Because "Google/Analytics.h" header is not available in the 'GoogleAnalytics sdk' as mentioned in Google's Official page.

我遇到了同样的问题。由于Xcode生成错误,我无法导入“Google / Analytics.h”标头。因为Google官方网页中提到的“GoogleAnalytics sdk”中没有“Google / Analytics.h”标题。

So, i just used following line

所以,我只是使用了以下行

#import "GAI.h"

Hope it will work just fine. Environment Xcode: 8.2 iOS :10.2

希望它能正常工作。环境Xcode:8.2 iOS:10.2

#4


2  

For swift 3:

对于swift 3:

    var configureError:NSError? = nil
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")
    let gai = GAI.sharedInstance()
    gai?.trackUncaughtExceptions = true
    gai?.logger.logLevel = GAILogLevel.verbose

#5


0  

I think it's better to send error to crashlytics, but continue executing an app:

我认为最好将错误发送到crashlytics,但继续执行应用程序:

func configureGoogleAnalytics() {
    var configureError: NSError? = nil
    GGLContext.sharedInstance().configureWithError(&configureError)
    if configureError != nil {
        Crashlytics.sharedInstance().recordError(configureError!)
    }
}

Also check this answer for newest way to add analytics.

另请查看此答案,了解添加分析的最新方法。

#1


29  

There are two options for implementation with Google Analytics using CocoaPods.

使用CocoaPods可以使用Google Analytics实施两种方法。

  1. pod 'Google/Analytics'
  2. pod'Google / Analytics'
  3. pod 'GoogleAnalytics'
  4. pod'GoogleAnalytics'

There are pros and cons between them.

他们之间有利有弊。

pod 'Google/Analytics'

pod'Google / Analytics'

  • need google configuration file(GoogleService-Info.plist)
  • 需要谷歌配置文件(GoogleService-Info.plist)
  • simple bridging header file. Just add #import <Google/Analytics.h> in bridging header file.
  • 简单的桥接头文件。只需在桥接头文件中添加#import 即可。
  • add import Googlein every file you want to implement google analytics.
  • 在每个要实施Google Analytics的文件中添加导入Google。

pod 'GoogleAnalytics'

pod'GoogleAnalytics'

  • no google configuration file(GoogleService-Info.plist)
  • 没有谷歌配置文件(GoogleService-Info.plist)
  • more complex bridging header file.
  • 更复杂的桥接头文件。

I prefer to use pod 'GoogleAnalytics' but I'll explain how to solve this issue using pod 'Google/Analytics' because the google official site recommends pod 'Google/Analytics'.

我更喜欢使用pod'GoogleAnalytics',但我会解释如何使用pod'Google / Analytics'解决此问题,因为谷歌官方网站推荐使用pod'Google / Analytics'。

  1. bridging header
  2. 桥头

You just need one line of code for google analytics.

您只需要一行代码用于Google Analytics。

#import <Google/Analytics.h>

Don't forget to set target-build setting for Objective-C-Bridging-Header. You have to provide correct path to enable Objective-C-Bridging-Header.

不要忘记为Objective-C-Bridging-Header设置目标构建设置。您必须提供正确的路径才能启用Objective-C-Bridging-Header。

Set Target-Build Setting-Objective-C-Bridging-Header $(SRCROOT)/$(PRODUCT_NAME)/projectName_Bridging_Header.h

设置Target-Build Setting-Objective-C-Bridging-Header $(SRCROOT)/ $(PRODUCT_NAME)/projectName_Bridging_Header.h

  1. AppDelegate.swift
  2. AppDelegate.swift
import Google

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
-> Bool { self.setupGoogleAnalytics()
..
     self.setupGoogleAnalytics()
..
 }

func setupGoogleAnalytics() {

    // Configure tracker from GoogleService-Info.plist.
    let configureError:NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    let gai = GAI.sharedInstance()
    gai.trackUncaughtExceptions = true  // report uncaught exceptions
    gai.logger.logLevel = GAILogLevel.Verbose  // remove before app release
}
  1. SomeViewController.swift
  2. SomeViewController.swift
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)

    if let default_tracker = GAI.sharedInstance().defaultTracker {
        #if DEBUG

            print("default tracker")

        #endif
    }

    //        let tracker = GAI.sharedInstance().defaultTracker
    let tracker = GAI.sharedInstance().trackerWithTrackingId("tracking_ID")
    tracker.set(kGAIScreenName, value: screenName)
    let builder = GAIDictionaryBuilder.createScreenView()
    tracker.send(builder.build() as [NSObject : AnyObject])

}

Why do I use trackerWithTrackingId instead of defaultTracker property? You could got an error if you use defaultTracker :

为什么我使用trackerWithTrackingId而不是defaultTracker属性?如果使用defaultTracker,则可能会出错:

fatal error: unexpectedly found nil while unwrapping an Optional value

致命错误:在展开Optional值时意外发现nil

defaultTracker property's initial value is nil, but it will be set after trackerWithTrackingId method is called. But it doesn't work perfectly sometimes. To avoid this issue, I recommend that use trackerWithTrackingId method directly.

defaultTracker属性的初始值为nil,但它将在trackerWithTrackingId方法被调用后设置。但它有时并不完美。为避免此问题,我建议直接使用trackerWithTrackingId方法。

I make the sample project using pod 'GoogleAnalytics'. You can get an idea from it. Good luck.

我使用pod'GoogleAnalytics'制作示例项目。你可以从中得到一个想法。祝你好运。

Test Env

测试环境

GoogleAnalytics 3.14

GoogleAnalytics 3.14

Xcode 7.2.1

Xcode 7.2.1

#2


8  

In Podfile

在Podfile中

pod 'Google/Analytics'

In YourFantasticProjectName-Bridging-Header.h

在YourFantasticProjectName-Bridging-Header.h中

#import "Google/Analytics.h"

You don't need this

你不需要这个

GGLContext.sharedInstance().configureWithError(&configureError)

You need to have a proper tracker

你需要一个合适的跟踪器

let gai = GAI.sharedInstance()
let tracker = gai.tracker(withTrackingId: "UA-12345678-1")

In order for live view to work in GA dashboard, you must track screen using GAIDictionaryBuilder and correct key kGAIScreenName

要使实时视图在GA仪表板中工作,您必须使用GAIDictionaryBuilder跟踪屏幕并更正密钥kGAIScreenName

tracker.set(kGAIScreenName, value: "this is my screen")
let event = GAIDictionaryBuilder.createScreenView()
tracker?.send(event!.build() as! [NSObject: Any])

In the same vein, to track events, you need to use GAIDictionaryBuilder as it will create dictionary with correct GA keys, and GA likes correct keys

同样,要跟踪事件,您需要使用GAIDictionaryBuilder,因为它将使用正确的GA键创建字典,GA喜欢正确的键

let event = GAIDictionaryBuilder.createEvent(withCategory: "category", action: "action", label: "level", value: NSNumber(value: 120))
tracker?.send(event!.build() as! [NSObject: Any])

It seems to work in the simulator too

它似乎也在模拟器中工作

#3


7  

I faced the same problem. I could not import the "Google/Analytics.h" header as Xcode generate error. Because "Google/Analytics.h" header is not available in the 'GoogleAnalytics sdk' as mentioned in Google's Official page.

我遇到了同样的问题。由于Xcode生成错误,我无法导入“Google / Analytics.h”标头。因为Google官方网页中提到的“GoogleAnalytics sdk”中没有“Google / Analytics.h”标题。

So, i just used following line

所以,我只是使用了以下行

#import "GAI.h"

Hope it will work just fine. Environment Xcode: 8.2 iOS :10.2

希望它能正常工作。环境Xcode:8.2 iOS:10.2

#4


2  

For swift 3:

对于swift 3:

    var configureError:NSError? = nil
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")
    let gai = GAI.sharedInstance()
    gai?.trackUncaughtExceptions = true
    gai?.logger.logLevel = GAILogLevel.verbose

#5


0  

I think it's better to send error to crashlytics, but continue executing an app:

我认为最好将错误发送到crashlytics,但继续执行应用程序:

func configureGoogleAnalytics() {
    var configureError: NSError? = nil
    GGLContext.sharedInstance().configureWithError(&configureError)
    if configureError != nil {
        Crashlytics.sharedInstance().recordError(configureError!)
    }
}

Also check this answer for newest way to add analytics.

另请查看此答案,了解添加分析的最新方法。