本文說明如何使用 Google Analytics (分析) SDK v3 管理將資料分派至 Google Analytics (分析)。
總覽
使用 iOS 版 Google Analytics (分析) SDK 收集到的資料會先儲存在本機,再分派至個別的執行緒給 Google Analytics (分析)。
必須在每個資料檢視的當地時區隔天上午 4 點前分派及接收資料。凡是之後收到的資料都不會顯示在報表中。舉例來說,如果命中在本機中午 11:59 加入佇列,則命中必須在 4 小時內 (上午 3:59) 分派在報表中。另一方面,在上午 12:00 時排入佇列的命中必須在 28 小時內分派,例如則要在報表中顯示。
定期派遣
根據預設,系統每 2 分鐘就會從 iOS 版的 Google Analytics (分析) SDK 分派資料。
// 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]; }
每當含有一或多個 Google Analytics (分析) 信標的要求時,dispatchWithCompletionHandler
方法都會將完成區塊做為參數,並呼叫完成區塊。這個函式會傳回結果,指出是否有其他要傳送的資料,以及/或最後一個要求是否成功。透過這個方法,您可以在應用程式於背景執行時,有效管理分派信標。
覆寫 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; }