在 ios swift 中实现谷歌分析 [英] Implement Google Analytics in ios swift

查看:27
本文介绍了在 ios swift 中实现谷歌分析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

第一步

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

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

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.

第 2 步

然后按照指南中的说明打开我的应用程序的 Project .xcworkspace 文件.

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

我的 Podfile 如下所示:

My Podfile looks like this:

# 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

XXXXXX 是我的项目名称.

Where XXXXXX is my Project's name.

步骤 3

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

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

步骤 4

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

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:

#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

其中XXXXX"是我的项目名称.

Where "XXXXX" is my Project's name.

步骤 5

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

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

AppDelegate.swift 导入谷歌分析

我也尝试过 import "Google/Analytics.h" 但出现另一个错误:导入声明中的预期标识符.

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

  • 我该如何解决这个问题,这样 XCode 才不会出现错误?
  • BridgingHeader 错了吗?我是否必须以某种方式指向它才能识别其内部标题?
  • 我是否必须为我现在缺少的 Google Analytics(分析)配置其他内容?

非常感谢.

推荐答案

使用 CocoaPods 通过 Google Analytics 实施有两种选择.

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

  1. pod 'Google/Analytics'
  2. podGoogleAnalytics"

两者各有利弊.

pod 'Google/Analytics'

  • 需要谷歌配置文件(GoogleService-Info.plist)
  • 简单的桥接头文件.只需在桥接头文件中添加 #import .
  • 在要实施谷歌分析的每个文件中添加import Google.

pod 'GoogleAnalytics'

  • 没有谷歌配置文件(GoogleService-Info.plist)
  • 更复杂的桥接头文件.

我更喜欢使用 pod 'GoogleAnalytics' 但我将解释如何使用 pod 'Google/Analytics' 解决这个问题因为 google 官方网站推荐 pod 'Google/Analytics'.

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'.

  1. 桥接标题

您只需要一行代码即可进行谷歌分析.

You just need one line of code for google analytics.

#import <Google/Analytics.h>

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

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.

设置目标-构建设置-目标-C-Bridging-Header$(SRCROOT)/$(PRODUCT_NAME)/projectName_Bridging_Header.h

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

  1. 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

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])

}

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

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

致命错误:在解包可选值时意外发现 nil

defaultTracker 属性的初始值为 nil,但之后会被设置trackerWithTrackingId 方法被调用.但它有时并不完美.为了避免这个问题,我建议直接使用 trackerWithTrackingId 方法.

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.

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

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

测试环境

谷歌分析 3.14

Xcode 7.2.1

Xcode 7.2.1

这篇关于在 ios swift 中实现谷歌分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆