Skip to content

Sesiones de seguimiento

Aprende a hacer un seguimiento de las sesiones a través del SDK de Braze.

About the session lifecycle

A session refers to the period of time the Braze SDK tracks user activity in your app after it’s launched. You can also force a new session by calling the changeUser() method.

By default, a session starts when openSession() is first called. If your app goes to the background and then returns to the foreground, the SDK will check if more than 10 seconds have passed since the session started (unless you change the default session timeout). If so, a new session will begin. Keep in mind that if the user closes your app while it’s in the background, session data may not be sent to Braze until they reopen the app.

Calling closeSession() will not immediately end the session. Instead, it will end the session after 10 seconds if openSession() isn’t called again by the user starting another activity.

By default, a session starts when you call Braze.init(configuration:). This occurs when the UIApplicationWillEnterForegroundNotification notification is triggered, meaning the app has entered the foreground.

If your app goes to the background, UIApplicationDidEnterBackgroundNotification will be triggered. When your app returns to the foreground, the SDK will check if more than 10 seconds have passed since the session started (unless you change the default session timeout). If so, a new session will begin.

By default, a session starts when you first call braze.openSession(). The session will remain active for up to 30 minutes of inactivity (unless you change the default session timeout or the user closes the app.

Suscribirse a las actualizaciones de la sesión

Paso 1: Suscribirse a las actualizaciones

Para suscribirte a las actualizaciones de la sesión, utiliza el método subscribeToSessionUpdates().

1
2
3
4
5
6
7
8
Braze.getInstance(this).subscribeToSessionUpdates(new IEventSubscriber<SessionStateChangedEvent>() {
  @Override
  public void trigger(SessionStateChangedEvent message) {
    if (message.getEventType() == SessionStateChangedEvent.ChangeType.SESSION_STARTED) {
      // A session has just been started
    }
  }
});
1
2
3
4
5
Braze.getInstance(this).subscribeToSessionUpdates { message ->
  if (message.eventType == SessionStateChangedEvent.ChangeType.SESSION_STARTED) {
    // A session has just been started
  }
}

Si registras una devolución de llamada de fin de sesión, se dispara cuando la aplicación vuelve al primer plano. La duración de la sesión se mide desde que la aplicación se abre o está en primer plano, hasta que se cierra o está en segundo plano.

1
2
3
4
5
6
7
8
9
10
11
// This subscription is maintained through a Braze cancellable, which will observe changes until the subscription is cancelled.
// You must keep a strong reference to the cancellable to keep the subscription active.
// The subscription is canceled either when the cancellable is deinitialized or when you call its `.cancel()` method.
let cancellable = AppDelegate.braze?.subscribeToSessionUpdates { event in
  switch event {
  case .started(let id):
    print("Session \(id) has started")
  case .ended(let id):
    print("Session \(id) has ended")
  }
}

Para suscribirte a un flujo asíncrono, puedes utilizar sessionUpdatesStream en su lugar.

1
2
3
4
5
6
7
8
for await event in braze.sessionUpdatesStream {
  switch event {
  case .started(let id):
    print("Session \(id) has started")
  case .ended(let id):
    print("Session \(id) has ended")
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This subscription is maintained through a Braze cancellable, which will observe changes until the subscription is cancelled.
// You must keep a strong reference to the cancellable to keep the subscription active.
// The subscription is canceled either when the cancellable is deinitialized or when you call its `.cancel()` method.
BRZCancellable *cancellable = [AppDelegate.braze subscribeToSessionUpdates:^(BRZSessionEvent * _Nonnull event) {
  switch (event.state) {
    case BRZSessionStateStarted:
      NSLog(@"Session %@ has started", event.sessionId);
      break;
    case BRZSessionStateEnded:
      NSLog(@"Session %@ has ended", event.sessionId);
      break;
    default:
      break;
  }
}];

En este momento, la suscripción a las actualizaciones de sesión no es compatible con el SDK de Web Braze.

Paso 2: Seguimiento de la sesión de prueba (opcional)

Para probar el seguimiento de la sesión, inicia una sesión en tu dispositivo, luego abre el panel de Braze y busca al usuario correspondiente. En su perfil de usuario, selecciona Resumen de sesiones. Si las métricas se actualizan como se espera, el seguimiento de la sesión funciona correctamente.

La sección de resumen de sesiones de un perfil de usuario que muestra el número de sesiones, la última fecha de uso y la primera fecha de uso.

Cambiar el tiempo de espera predeterminado de la sesión

Puedes cambiar el tiempo que transcurre antes de que una sesión caduque automáticamente.

Por defecto, el tiempo de espera de la sesión está predeterminado en 10 segundos. Para cambiar esto, abre tu archivo braze.xml y añade el parámetro com_braze_session_timeout. Puede establecerse en cualquier número entero mayor o igual que 1.

1
2
<!-- Sets the session timeout to 60 seconds. -->
<integer name="com_braze_session_timeout">60</integer>

Por defecto, el tiempo de espera de la sesión está predeterminado en 10 segundos. Para cambiar esto, configura sessionTimeout en el objeto configuration que se pasa a init(configuration). Puede establecerse en cualquier número entero mayor o igual que 1.

1
2
3
4
5
6
7
8
// Sets the session timeout to 60 seconds
let configuration = Braze.Configuration(
  apiKey: "<BRAZE_API_KEY>",
  endpoint: "<BRAZE_ENDPOINT>"
)
configuration.sessionTimeout = 60;
let braze = Braze(configuration: configuration)
AppDelegate.braze = braze
1
2
3
4
5
6
7
// Sets the session timeout to 60 seconds
BRZConfiguration *configuration =
  [[BRZConfiguration alloc] initWithApiKey:brazeApiKey
                                  endpoint:brazeEndpoint];
configuration.sessionTimeout = 60;
Braze *braze = [[Braze alloc] initWithConfiguration:configuration];
AppDelegate.braze = braze;

Por defecto, el tiempo de espera de la sesión está predeterminado en 30 minutos. Para cambiar esto, pasa la opción sessionTimeoutInSeconds a tu initialize función. Puede establecerse en cualquier número entero mayor o igual que 1.

1
2
// Sets the session timeout to 15 minutes instead of the default 30
braze.initialize('YOUR-API-KEY-HERE', { sessionTimeoutInSeconds: 900 });
¿QUÉ TAN ÚTIL FUE ESTA PÁGINA?
New Stuff!