在iOS中快速实施Google Analytics [英] Implement Google Analytics in ios swift

查看:101
本文介绍了在iOS中快速实施Google Analytics的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循Google Analytics(分析)for iOS(developers.google.com/analytics/devguides/collection/ios/v3/?ver=swift)指南,我的Swift代码项目中有错误,我无法修复。
我正在使用XCode 6.4,Swift和iOS部署目标8.1。



第1步

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

 更新本地规格库

CocoaPods 1.0.0.beta.2可用。
更新使用:`gem install cocoapods --pre`
[!]这是我们希望您尝试的测试版本。

有关更多信息,请参阅http://blog.cocoapods.org
和此版本的http://git.io/BaH8pQ的CHANGELOG。

分析依赖项
下载依赖项
使用Google(1.0.7)
使用GoogleAnalytics(3.14.0)
使用GoogleNetworkingUtilities(1.0.0)
使用GoogleSymbolUtilities(1.0.3)
使用GoogleUtilities(1.1.0)
生成Pods项目
集成客户端项目
发送统计信息
Pod安装完成!
Podfile有1个依赖项,并且安装了5个总的窗格。

步骤2

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



我的Podfile如下所示:

 #取消注释此行为您的项目定义全球平台
#platform:ios,'8.0'
#取消注释此行使用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是我的项目名称



第3步
$ b

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



通过选择File> New> File> iOS> Source> Header File创建了 BridgingHeader
我将它命名为 BridgingHeader.h ,它位于我的Project的根目录中。 b

$ b

  #ifndef XXXXX_BridgingHeader_h 
#define XXXXX_BridgingHeader_h

#importGoogle / Analytics.h
#import< Google / Analytics.h>
#includeGAI.h

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

#importLibraries / GoogleAnalytics / GAI.h
#importLibraries / GoogleAnalytics / GAIFields.h
#importLibraries / GoogleAnalytics / GAILogger.h
#importLibraries / GoogleAnalytics / GAITracker.h
#importLibraries / GoogleAnalytics / GAIDictionaryBuilder.h

#endif

其中XXXXX是我的项目名称。



第5步

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



AppDelegate.swift导入Google Analytics(分析)



我也尝试了导入Google / Analytics.h导入声明中的预期标识符




  • 如何解决此问题所以XCode不会给我错误?
  • BridgingHeader错了吗?我是否必须指出此方式来识别其内部标头?

  • 是否必须为我现在缺少的Google Analytics配置其他内容?

使用CocoaPods进行Google Analytics实施有两种选择。


  1. pod'Google Analytics(分析)'

  2. pod'GoogleAnalytics'


    他们之间有利弊。



    pod'Google / Analytics'


    $ b

    • 需要谷歌配置文件(GoogleService-Info.plist)
    • 简单的桥接头文件。只需在桥接头文件中添加 #import< Google / Analytics.h> 即可。



    pod'GoogleAnalytics' >


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



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


    1. 桥接头

    您只需要一行代码用于Google Analytics(分析)。

      #import< ;谷歌/ Analytics.h> 

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

    设置目标生成设置 - 目标C-桥接 - Header
    $(SRCROOT)/ $(PRODUCT_NAME)/projectName_Bridging_Header.h



    1. AppDelegate .swift



      import Google 

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

    func setupGoogleAnalytics(){

    //从GoogleService-Info.plist中配置跟踪器。
    让configureError:NSError?
    GGLContext.sharedInstance()。configureWithError(& configureError)
    assert(configureError == nil,配置Google服务时出错:\(configureError))

    let gai = GAI.sharedInstance()
    gai.trackUncaughtExceptions = true //报告未捕获的异常
    gai.logger.logLevel = GAILogLevel.Verbose //在应用发布之前删除
    }




    1. SomeViewController.swift


    $ b

      override func viewWillAppear(animated:Bool){
    super.viewWillAppear(true)

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

    print(default tracker)

    #endif $ b $ trackback = GAI.sharedInstance()。trackerWithTrackingId(tracking_ID)
    tracker.set() kGAIScreen名称,值:screenName)
    let builder = GAIDictionaryBuilder.createScreenView()
    tracker.send(builder.build()as [NSObject:AnyObject])

    }

    为什么我使用trackerWithTrackingId代替defaultTracker属性?如果您使用defaultTracker,则可能会出现错误:

    致命错误:意外地发现nil,同时展开可选值

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



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


    测试环境

    GoogleAnalytics 3.14 p>

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

    Step 1

    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.
    

    Step 2

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

    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
    

    Where XXXXXX is my Project's name.

    Step 3

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

    Step 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:

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

    Step 5

    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

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

    • How can I fix this so XCode doesn't give me errors?
    • Is the BridgingHeader wrong? Do I have to point at this somehow to recognize its inner headers?
    • Do I have to configure something else for the Google Analytics that I am missing right now?

    Thank you very much.

    解决方案

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

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

    There are pros and cons between them.

    pod 'Google/Analytics'

    • need google configuration file(GoogleService-Info.plist)
    • simple bridging header file. Just add #import <Google/Analytics.h> in bridging header file.
    • add import Googlein every file you want to implement google analytics.

    pod 'GoogleAnalytics'

    • no google configuration file(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'.

    1. bridging header

    You just need one line of code for 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.

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

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

    fatal error: unexpectedly found nil while unwrapping an Optional value

    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.

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

    Test Env

    GoogleAnalytics 3.14

    Xcode 7.2.1

    这篇关于在iOS中快速实施Google Analytics的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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