本文档将介绍如何使用 iOS 版 Google Analytics(分析)SDK v3 管理将数据调度到 Google Analytics(分析)的工作。
概览
使用 iOS 版 Google Analytics(分析)SDK 收集的数据会先存储在本地,然后才会在单独的线程中调度到 Google Analytics(分析)。
数据必须在各数据视图本地时区的次日凌晨 4 点之前进行调度和接收。送达时间晚于此时限的数据将不会出现在报告中。例如,如果某次匹配在本地时间晚上 11:59 加入队列,则必须在 4 个小时内(凌晨 3:59 之前)调度到 Google Analytics(分析),否则该匹配无法出现在报告中。另一方面,凌晨 12:00 加入队列的命中必须在 28 小时内调度,即次日凌晨 3:59,才能在报告中显示。
定期调度
默认情况下,iOS 版 Google Analytics(分析)SDK 会每隔 2 分钟调度一次数据。
// Set the dispatch interval in seconds. // 2 minutes (120 seconds) is the default value. [GAI sharedInstance].dispatchInterval = 120;
将此值设为负数会停用定期调度,在这种情况下,如果您希望向 Google Analytics(分析)调度数据,则需要使用手动调度。
// Disable periodic dispatch by setting dispatch interval to a value less than 1. [GAI sharedInstance].dispatchInterval = 0;
如果用户的网络连接断开,或是用户在匹配数据尚待调度时就退出了您的应用,那么您的匹配数据会继续存储在本地。这些数据会在您的应用下次运行并发出调度请求时进行调度。
手动调度
要手动调度匹配数据(比如当您知道应用正在使用设备的网络连接调度其他数据时),请使用:
[[GAI sharedInstance] dispatch];
后台调度
要在 iOS 应用上启用后台调度,请执行以下操作:
- 为
dispatchHandler
添加属性。 - 实现
sendHitsInBackground
方法。 -
替换
applicationDidEnterBackground
方法。 - 替换
applicationWillEnterForeground
方法。
为 dispatchHandler
添加属性
在 AppDelegate
类的实现文件 (AppDelegate.m
) 中,将以下属性添加到 @implementation AppDelegate
之前:
@interface AppDelegate () @property(nonatomic, copy) void (^dispatchHandler)(GAIDispatchResult result); @end @implementation AppDelegate // ...
实现 sendHitsInBackground
方法
在 AppDelegate
类中,实现 sendHitsInBackground
方法,以便在应用进入后台时发送命中:
// This method sends any queued hits when the app enters the background. - (void)sendHitsInBackground { __block BOOL taskExpired = NO; __block UIBackgroundTaskIdentifier taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ taskExpired = YES; }]; if (taskId == UIBackgroundTaskInvalid) { return; } __weak AppDelegate *weakSelf = self; self.dispatchHandler = ^(GAIDispatchResult result) { // Send hits until no hits are left, a dispatch error occurs, or // the background task expires. if (result == kGAIDispatchGood && !taskExpired) { [[GAI sharedInstance] dispatchWithCompletionHandler:weakSelf.dispatchHandler]; } else { [[UIApplication sharedApplication] endBackgroundTask:taskId]; } }; [[GAI sharedInstance] dispatchWithCompletionHandler:self.dispatchHandler]; }
dispatchWithCompletionHandler
方法将完成块作为参数,每当包含一个或多个 Google Analytics(分析)信标的请求完成时,都会调用该完成块。它会返回一个结果,指示是否还有更多数据要发送和/或上一个请求是否成功。使用此方法,您可以在应用转入后台时有效管理调度信标。
替换 applicationDidEnterBackground
方法
替换 AppDelegate
类中的 applicationDidEnterBackground
方法以调用 sendHitsInBackground
方法,该方法会在应用进入后台时发送命中:
- (void)applicationDidEnterBackground:(UIApplication *)application { [self sendHitsInBackground]; }
替换 applicationWillEnterForeground
方法
替换 AppDelegate
类的 applicationWillEnterForeground
方法以恢复调度间隔。例如:
- (void)applicationWillEnterForeground:(UIApplication *)application { // Restores the dispatch interval because dispatchWithCompletionHandler // has disabled automatic dispatching. [GAI sharedInstance].dispatchInterval = 120; }