高级配置 - iOS SDK

本文档将大略介绍 iOS 版 Google Analytics(分析)SDK v3 的高级配置功能。

概览

iOS 版 Google Analytics(分析)SDK 提供了一个 GAITracker 类用于设置并向 Google Analytics(分析)发送数据,并提供了一个 GAI 单例来作为您的实现方案的全局配置值的接口。

初始化

您需要先通过 GoogleAnalytics 单例至少初始化一个跟踪器,然后才能开始跟踪数据。在初始化时,您需要提供跟踪器的名称和一个 Google Analytics(分析)媒体资源 ID:

// Initialize a tracker using a Google Analytics property ID.
[[GAI sharedInstance] trackerWithTrackingId:@"UA-XXXX-Y"];

现在此跟踪器就可用于设置并向 Google Analytics(分析)发送数据了。

设置和发送数据

为了向 Google Analytics(分析)发送数据,您需要在跟踪器中设置“参数-值”对的映射关系,并通过 setsend 方法来发送这些数据:

/*
 * Send a screen view to Google Analytics by setting a map of parameter
 * values on the tracker and calling send.
 */

// Retrieve tracker with placeholder property ID.
id<GAITracker> tracker = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXXX-Y"];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"appview", kGAIHitType, @"Home Screen", kGAIScreenName, nil];
[tracker send:params];

GAIDictionaryBuilder 类可以简化构建匹配的过程,因此在大多数情况下建议您使用此类。这样,我们便可以使用更少的代码量来发送同样的屏幕浏览匹配:

// Previous V3 SDK versions.
// Sending the same screen view hit using [GAIDictionaryBuilder createAppView]
// [tracker send:[[[GAIDictionaryBuilder createAppView] set:@"Home Screen"
//                                                   forKey:kGAIScreenName] build]];

// SDK Version 3.08 and up.
// Sending the same screen view hit using [GAIDictionaryBuilder createScreenView]
[tracker send:[[[GAIDictionaryBuilder createScreenView] set:@"Home Screen"
                                                     forKey:kGAIScreenName] build]];

Measurement Protocol“&”符号语法

您可以选择在 Builder 中设置值,以便为一次匹配设置该值;也可以使用 Measurement Protocol“&”符号语法在跟踪器对象本身中设置值,以便为所有后续匹配设置该值。

// Sending the same screen view hit using ampersand syntax.
// Previous V3 SDK versions.
// [tracker send:[[[GAIDictionaryBuilder createAppView] set:@"Home Screen"
//                                                   forKey:kGAIScreenName] build]];

// SDK Version 3.08 and up.
[tracker send:[[[GAIDictionaryBuilder createScreenView] set:@"Home Screen"
                                                     forKey:kGAIScreenName] build]];

如要了解可用 Measurement Protocol 参数的完整列表,请参阅 Measurement Protocol 参数参考

将值应用于多次匹配

直接在跟踪器中设置的值将是持久值,并会应用于多次匹配,如下例所示:

// May return nil if a tracker has not yet been initialized with
// a property ID.
id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];

// Set screen name on the tracker to be sent with all hits.
[tracker set:kGAIScreenName
       value:@"Home Screen"];

// Send a screen view for "Home Screen".
// [tracker send:[[GAIDictionaryBuilder createAppView] build]];   // Previous V3 SDK versions.
[tracker send:[[GAIDictionaryBuilder createScreenView] build]];   // SDK Version 3.08 and up.

// This event will also be sent with &cd=Home%20Screen.
[tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"UX"
                                                      action:@"touch"
                                                       label:@"menuButton"
                                                       value:nil] build]];

// Clear the screen name field when we're done.
[tracker set:kGAIScreenName
       value:nil];

只有在想要使值成为持久值并应用于多次匹配时,您才应当直接在跟踪器中设置值。在跟踪器中设置屏幕名称是一种可取的做法,因为同样的值可以应用于一系列的屏幕浏览和事件匹配。不过,不建议在跟踪器中设置匹配类型等字段,因为此类字段很可能随每次匹配而改变。

使用多个跟踪器

您可以在一个实现实例中使用多个跟踪器,以便向多个媒体资源发送数据:

id<GAITracker> t1 = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXXX-1"];

// Trackers may be named. By default, name is set to the property ID.
id<GAITracker> t2 = [[GAI sharedInstance] trackerWithName:@"altTracker"
                                                     trackingId:@"UA-XXXX-2"];

[t1 set:kGAIScreenName
        value:@"Home Screen"];

[t2 set:kGAIScreenName
        value:NSStringFromClass([self class])];

// Send a screenview to UA-XXXX-1.
// [t1 send:[[GAIDictionaryBuilder createAppView] build]];   // Previous V3 SDK versions.
[t1 send:[[GAIDictionaryBuilder createScreenView] build]];   // SDK Version 3.08 and up.

// Send a screenview to UA-XXXX-2.
// [t2 send:[[GAIDictionaryBuilder createAppView] build]];   // Previous V3 SDK versions.
[t2 send:[[GAIDictionaryBuilder createScreenView] build]];   // SDK Version 3.08 and up.

自动屏幕衡量和未捕获异常衡量等自动衡量功能都只会使用一个跟踪器来向 Google Analytics(分析)发送数据。如果您在使用这些功能,但又想使用其他跟踪器来发送数据,则需要采取手动方式。

作为参考,自动屏幕衡量会使用 GAITrackedViewControllertracker 属性中指定的跟踪器。未捕获异常衡量会使用 GAI 实例中指定的默认跟踪器。

使用默认跟踪器

Google Analytics(分析)会维持一个默认跟踪器。第一个初始化的跟踪器将成为默认跟踪器,但您也可以覆盖此设置:

// t1 becomes the default tracker because it is the first tracker initialized.
id<GAITracker> t1 = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXXX-1"];

id<GAITracker> t2 = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXXX-2"];

// Returns t1.
id<GAITracker> defaultTracker = [[GAI sharedInstance] defaultTracker];

// Hit sent to UA-XXXX-1.
// Previous V3 SDK versions.
// [defaultTracker send:[[[GAIDictionaryBuilder createAppView]
//                 set:@"Home Screen" forKey:kGAIScreenName] build]];

// SDK Version 3.08 and up.
[defaultTracker send:[[[GAIDictionaryBuilder createScreenView]
                set:@"Home Screen" forKey:kGAIScreenName] build]];

// Override the default tracker.
[[GAI sharedInstance] setDefaultTracker:t2];

// Returns t2.
defaultTracker = [[GAI sharedInstance] defaultTracker];

// Hit sent to UA-XXXX-2.
// Previous V3 SDK versions.
// [defaultTracker send:[[[GAIDictionaryBuilder createAppView]
//                        set:NSStringFromClass([self class])
//                     forKey:kGAIScreenName] build]];

// SDK Version 3.08 and up.
[defaultTracker send:[[[GAIDictionaryBuilder createScreenView]
                       set:NSStringFromClass([self class])
                    forKey:kGAIScreenName] build]];

抽样

您可以启用客户端抽样,以限制向 Google Analytics(分析)发送的匹配数量。如果您的应用有大量用户,或因其他原因而向 Google Analytics(分析)发送大量数据,则启用抽样有助于确保报告不发生中断。

例如,要将客户端抽样率设为 50%,请使用以下代码:

// Assumes a tracker has already been initialized with a property ID, otherwise
// getDefaultTracker returns nil.
id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];

// Set a sample rate of 50%.
[tracker set:kGAISampleRate value:@"50.0"];

应用级选择停用

您可以启用“应用级选择停用”标记,以便在整个应用内停用 Google Analytics(分析)。请注意,每次启动应用后都必须设置该标记,否则其默认设置为 NO

要获取应用级选择停用设置,请使用以下代码:

// Get the app-level opt out preference.
if ([GAI sharedInstance].optOut) {
  ... // Alert the user they have opted out.
}

要设置应用级选择停用,请使用以下代码:

// Set the app-level opt out preference.
[[GAI sharedInstance] setOptOut:YES];

对 IP 地址进行匿名处理

启用匿名处理 IP 功能可以告知 Google Analytics(分析)匿名化处理由 SDK 发送的 IP 信息,即在存储前删除 IP 地址的最后一个八位位组。

下例显示了如何启用跟踪器的匿名处理 IP 功能:

[tracker set:kGAIAnonymizeIp value:@"1"];

匿名处理 IP 功能可以随时设置。

测试和调试

iOS 版 Google Analytics(分析)SDK 提供了多种工具,可让您更轻松地进行测试和调试。

Dry Run

SDK 提供了 dryRun 标志,如果设置了此标志,则不会向 Google Analytics(分析)发送任何数据。在您对实现方案进行测试或调试时,如果不想测试数据出现在您的 Google Analytics(分析)报告中,就应当设置 dryRun 标志。

要设置 dryRun 标志,请使用以下代码:

[[GAI sharedInstance] setDryRun:YES];

Logger

GAILogger 协议用于处理来自 SDK 的实用讯息,有以下详细程度可选:errorwarninginfoverbose

SDK 会初始化一个标准 Logger 实现,默认情况下只会记录发送到控制台的警告或错误讯息。要设置 Logger 的详细程度,请使用以下代码:

// Set the log level to verbose.
[[GAI sharedInstance].logger setLogLevel:kGAILogLevelVerbose];

您也可以使用自定义的Logger实现:

// Provide a custom logger.
[[GAI sharedInstance].logger = [[CustomLogger alloc] init];

完整示例

下例显示了初始化 Google Analytics(分析)实现和发送一次屏幕浏览所需的代码。

接下来,在第一个屏幕向用户显示时,衡量一次屏幕浏览:

一般情况下,实现的初始化可以从应用代理中完成,如下例所示:

//
//  AppDelegate.h
//
#import <UIKit/UIKit.h>
#import "GAI.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) id<GAITracker> tracker;

@end

//
//  AppDelegate.m
//
#import "AppDelegate.h"

/** Google Analytics configuration constants **/
static NSString *const kGaPropertyId = @"UA-XXXX-Y"; // Placeholder property ID.
static NSString *const kTrackingPreferenceKey = @"allowTracking";
static BOOL const kGaDryRun = NO;
static int const kGaDispatchPeriod = 30;

@interface AppDelegate ()

- (void)initializeGoogleAnalytics;

@end

@implementation AppDelegate
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [GAI sharedInstance].optOut =
    ![[NSUserDefaults standardUserDefaults] boolForKey:kTrackingPreferenceKey];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Do other work for customization after application launch
    // then initialize Google Analytics.
    [self initializeGoogleAnalytics];

    return YES;
}

- (void)initializeGoogleAnalytics {

    [[GAI sharedInstance] setDispatchInterval:kGaDispatchPeriod];
    [[GAI sharedInstance] setDryRun:kGaDryRun];
    self.tracker = [[GAI sharedInstance] trackerWithTrackingId:kGaPropertyId];
}

// The rest of the app delegate code omitted.

@end

然后,在某个视图向用户显示时衡量一次屏幕浏览:

//
// MyViewController.m
//
#import "MyViewController.h"
#import "AppDelegate.h"
#import "GAI.h"
#import "GAIFields.h"
#import "GAITracker.h"
#import "GAIDictionaryBuilder.h"

@implementation MyViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // 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.
    [[GAI sharedInstance].defaultTracker set:kGAIScreenName
                                       value:@"Home Screen"];

    // Send the screen view.
    // Previous V3 SDK versions.
    // [[GAI sharedInstance].defaultTracker
    //     send:[[GAIDictionaryBuilder createAppView] build]];

    // SDK Version 3.08 and up.
    [[GAI sharedInstance].defaultTracker
        send:[[GAIDictionaryBuilder createScreenView] build]];
}