iOS Dev iOS Dev - 5 months ago 73
iOS Question

How can I stop Google analytics tracking session when my app enters into background?

Using Google analytics v3 for my iOS app.

I tried to manually stop the current session when my app enters background and start a new session when my App enters foreground.

But it fails.

Here is my code :

In Appdelegate.m

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{
[GAI sharedInstance].trackUncaughtExceptions = YES;
[GAI sharedInstance].dispatchInterval = 20;
[[[GAI sharedInstance] logger] setLogLevel:kGAILogLevelError];
[[GAI sharedInstance] trackerWithTrackingId:@"UA-54600000-1"];

NSLog(@"Analytics Started");
}


and in

- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Here
// I WANT TO CLOSE THE CURRENT SESSION
}


and in

- (void)applicationWillEnterForeground:(UIApplication *)application
{
// HERE
// I WANT TO START A NEW SESSION
}

Answer

You can enable an app-level opt out flag that will disable Google Analytics across the entire app. Once set, the flag will persist for the life of the app or until it is reset.

- (void)applicationDidEnterBackground:(UIApplication *)application
{
 //  Here
 // THE CURRENT SESSION  

  [[GAI sharedInstance].setOptOut = YES];
  }


- (void)applicationWillEnterForeground:(UIApplication *)application
{
//   HERE
//    START A NEW SESSION

// Get a new tracker.
id newTracker = [[GAI sharedInstance]trackerWithTrackingId:@"UA-NEW-TRACKING-ID");

// Set the new tracker as the default tracker, globally.
[GAI sharedInstance].defaultTracker = newTracker;
}

need ref on more knowledge use this google analytics link

additional information have a nice tutorial

Comments