Skip to content

Latest commit

 

History

History
247 lines (188 loc) · 8.16 KB

File metadata and controls

247 lines (188 loc) · 8.16 KB
title description sidebar_position
Session reporting
Upload session reports from your React Native application using the Embrace SDK
5

Session reporting

Now that you’ve added the Embrace SDK to your project and can login to the Embrace dashboard, you’re ready to create your first session. Here are the steps you’ll be taking to create your first session.

  1. Start Embrace SDK in the native side
  2. Initialize Embrace SDK in the JavaScript side
  3. Build and run the application
  4. Trigger a session upload

Start Embrace SDK in the native side

:::info If you made use of the automated setup script from the Adding the Embrace SDK or the Expo config plugin then these steps will already have been completed for you. :::

Starting the Embrace SDK from the native side ensures that telemetry collection begins as early as possible in the app lifecycle. Without this step the native SDK will not start until the React Native bridge has loaded and the JavaScript initialize call executes, which means native crashes, ANRs, and app startup performance that occur before that point would be missed.

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

Create a new EmbraceInitializer.swift file in your project with the following contents:

import Foundation
import EmbraceIO

@objcMembers class EmbraceInitializer: NSObject {
    static func start() -> Void {
        do {
            try Embrace
                .setup(
                    options: Embrace.Options(
                        appId: "__APP_ID__", // 5 digits string
                        platform: .reactNative
                    )
                )
                .start()
        } catch let e {
            print("Error starting Embrace \(e.localizedDescription)")
        }
    }
}

:::info Once the iOS SDK is initialized in this way, any configuration parameters passed through the JavaScript side with sdkConfig.ios are ignored. Additional configuration can be applied when setting up the iOS SDK. :::

If your app delegate is in Swift you can then simply add a call EmbraceInitializer.start() to the start of the application method in your app delegate like:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        EmbraceInitializer.start()

        // rest of the logic
    }
}

If your app delegate is in Objective-c and this is the first swift file in your project then Xcode will prompt you to create a Bridging header file which you should accept. Next, in your AppDelegate.m|mm file you will need to add an import to your project's auto generated Swift header #import "ProductModuleName-Swift.h" (substituting your product's module name, see Apple's docs), and then add a call to [EmbraceInitializer start]; to the start of the application method in your app delegate like the following:

#import "AppDelegate.h"
#import "ProductModuleName-Swift.h"

...

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [EmbraceInitializer start];

  // rest of the logic
}

If you are using Expo you may need an additional #import <ExpoModulesCore-Swift.h> import before the line that imports your product's auto generated header, see this issue for more details.

Open the MainApplication.java file (usually located at <project root>/android/app/src/main/java/com/<MyApp>/MainApplication.java) and add the following to start Embrace:

import io.embrace.android.embracesdk.Embrace;

...

public class MainApplication extends Application implements ReactApplication {

    @Override
    public void onCreate() {
        super.onCreate();

        // Add this line right after the super.onCreate();
        Embrace.getInstance().start(this);
    }
}

Initializing Embrace SDK without an app ID or token

If you prefer to send the data into a custom backend avoiding Embrace you should skip the app_id / token values from both platform configurations. For more information about it you can visit the how to Use without an Embrace account section.

Initialize Embrace SDK in the JavaScript side

In addition to starting the native SDK, you must also call initialize on the JavaScript side as early as possible in your application. This sets up JavaScript-specific tracking including unhandled JS exceptions, React component errors, JS bundle change detection, and version metadata. If the native SDK was already started in the previous step, the JS initialize call will detect this and skip the native startup, but it will still apply the JavaScript-layer instrumentation that the native side cannot provide.

With hooks

The SDK exposes a hook that handles the initialization of Embrace in a React-friendly way:

import React, { useEffect, useState } from 'react'
import { useEmbrace } from '@embrace-io/react-native';

const App = () => {
  // minimum of configuration required
  const {isPending, isStarted} = useEmbrace({
    ios: {
      appId: "__APP_ID__", // 5 digits string
    },
  });


  if (isPending) {
    return (
      <View>
        <Text>Loading Embrace</Text>
      </View>
    );
  } else {
    if (!isStarted) {
      console.log('An error occurred during Embrace initialization');
    }
  }

  // regular content of the application
  return (
    ...
  );
}

export default App

Without hooks

import React, { useEffect, useState } from 'react'
import { initialize } from '@embrace-io/react-native';

const App = () => {
  useEffect(() => {
    const initEmbrace = async () => {
      try {
        const isStarted = await initialize({
          sdkConfig: {
            ios: {
              appId: "abcdf",
            },
          },
        });

        if (isStarted) {
          // do something
        }
      } catch {
        console.log("Error initializing Embrace SDK");
      }
    };

    initEmbrace();
  }, []); // Empty array for mount only in example; you should only initialize the Embrace SDK once.

  // regular content of the application
  return (
    ...
  );
}

export default App

In both cases, you should use these methods to initialize the React Native Embrace SDK at the top level of your application as early as possible and only once to prevent side effects in the JavaScript layer.

Build and run the application

Now you're ready to build and run the application. Launch the application how you usually would during development.

:::info If you encounter any errors, please get in touch on Slack and we can assist you. :::

Trigger a session upload

To trigger a session upload, simply background and then foreground the app, or stop the application by either force killing it or using the stop button in either Xcode for iOS or Android Studio for Android. Now run the application again. This second launch will upload the previous session immediately. Refresh the dashboard in your browser and you should see the session reported.


Congratulations! At this point you've completed a basic integration of Embrace. Embrace is already collecting interesting data from your application. You can see this data by browsing around the timeline page for the session you just captured.

Up next, you'll be learning about uploading crash reports.