当应用在iOS上的后台运行时发送Google Analytics事件

时间:2017-09-28 22:27:49

标签: ios objective-c google-analytics

当iOS应用移动到后台时发送事件时Google分析的行为是什么。那些活动是否适合服务?我们是否必须专门调用[[GAI sharedInstance] dispatch];在那些情况下?

1 个答案:

答案 0 :(得分:0)

首先,你可以按照你的建议做,你可以:

[[GAI sharedInstance] dispatch];

Google Analytics背景调度here上有第二个,它基本上为您提供了这种方法:

// 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];
}

覆盖applicationDidEnterBackground,如下所示:

- (void)applicationDidEnterBackground:(UIApplication *)application {
  [self sendHitsInBackground];
}

覆盖applicationWillEnterForeground,如下所示:

- (void)applicationWillEnterForeground:(UIApplication *)application {
  // Restores the dispatch interval because dispatchWithCompletionHandler
  // has disabled automatic dispatching.
  [GAI sharedInstance].dispatchInterval = 120;
}