# Apptics React Native

React Native library for Apptics, wrapper around Apptics Native iOS and Android SDK.

#### Prerequisites

- Requires React Native v0.76+
- [Setup development environment for React Native](https://reactnative.dev/docs/environment-setup)

The library ships as a TurboModule with codegen specs, and works on both the New
Architecture and the legacy bridge — on the legacy bridge it falls back to
`NativeModules` automatically, so no extra configuration is needed either way.

#### Install Apptics

Navigate to your app's root directory in terminal to install the `@zoho_apptics/apptics-react-native` package.

```plaintext
npm install @zoho_apptics/apptics-react-native
```

#### Initialize Apptics

Apptics requires you to perform platform specific initialization steps.

#### intialization steps for Apple platforms

1. Register your app and download `apptics-config.plist` from Apptics web console.
2. Once you have created the Project and added your app, download the apptics-config.plist, and move the file into the Xcode project root folder and add the config file to the main target.
3. Add pre-build scripts.

To add a Run Script via podfile.

```plaintext
source 'https://github.com/CocoaPods/Specs.git'
  target 'MAIN TARGET' do

    # Pre build script will register the app version, upload dSYM file to the server and add apptics specific information to the main info.plist which will be used by the SDK.
    script_phase :name => 'Apptics pre build', :script => 'sh "./Pods/Apptics-SDK/scripts/run" --upload-symbols-for-configurations="Release, Appstore"', :execution_position => :before_compile

  end
```

Or add a Run Script manually.

- In the project navigator, select your project.
- Select the target you want to modify.
- Click the Build Phases tab. Click the Add button (+), then choose “New Run Script Phase” from the pop-up menu and rename it as 'Apptics pre build.'
- Click the disclosure triangle for the newly added Run Script phase.
- In the Shell text field, enter the script below.

  ```
  sh "./Pods/Apptics-SDK/scripts/run" --upload-symbols-for-configurations="Release, Appstore"
  ```

#### Important:

- Adding pre-build scripts is mandatory.
- In the pre-build script, we upload dSYM to the server (optional), register the app with the Apptics server, and add the necessary information of the app version into the apptics-config.plist which is used by the SDK to send the data to the Apptics server.
- Always make sure 'Copy Bundle Resources' below the 'Compile Sources' and 'Apptics pre build' is above 'Compile Sources'.

Build script usage:

run --upload-symbols-for-configurations="Release, Appstore" --config-file-path="YOUR_PATH/apptics-config.plist" --app-group-identifier="group.com.company.application \[Optional\]"

- --config-file-path pass your config file path if it is not added to your project root.
- --app-group-identifier if you have enabled app group identifier for your app's target.
- --upload-symbols-for-configurations String, an optional parameter to pass your configuration name debug, release, or add a custom name with comma-separated for which the dSYMs will be uploaded without any prompt during App Store submission process via CI, CT, and CD.

For more details on how to configure for multiple projects please visit [iOS user guide](https://www.zoho.com/apptics/resources/SDK/iOS/integration.html)

1. Build the Xcode project and check for any issues and skip to 'Event Tracking'.

### Android intialization steps

1. Register your app and download `apptics-config.json` from Apptics web console.
2. Place apptics-config.json file in **app/** directory (Root of the Android Studio app module).
3. Add apptics-plugin classpath and zoho maven url in project level **build.gradle**

   ```groovy
   buildscript {
       repositories {
           maven {
               url "https://maven.zohodl.com/"
           }
       }
       dependencies {
           classpath "com.zoho.apptics:apptics-plugin:0.2.4"
       }
   }
   allprojects {
       repositories {
           maven {
               url "https://maven.zohodl.com/"
           }
       }
   }
   ```

4. Apply apptics-plugin and enable event tracking in app level gradle **(app/build.gradle)**

   ```groovy
   apply plugin: "com.android.application"
   apply plugin: "apptics-plugin"

   ```

5. Rebuild the Android project. (Build -> Rebuild in Android Studio)
6. Initialize Apptics in JS.

   ```plaintext
   import { Apptics } from '@zoho_apptics/apptics-react-native';

   // Initialize with automatic screen tracking enabled (default)
   Apptics.init();

   // Or initialize with automatic screen tracking disabled
   Apptics.init(false);
   ```

#### Crash Tracking.

Initialize react native crash handler.

```plaintext
import { Apptics } from '@zoho_apptics/apptics-react-native';

React.useEffect(() => {
    Apptics.initCrashTracker()
  }, []);
```

Crashes are only reported from release builds. In debug builds (`__DEV__`) the
handler is installed but nothing is sent to the server.

Report a caught error as a non-fatal exception.

```plaintext
import { Apptics } from '@zoho_apptics/apptics-react-native';

try {
  doSomething();
} catch (error) {
  Apptics.reportError(error);
}
```

Attach custom properties to crash reports.

```plaintext
import { Apptics } from '@zoho_apptics/apptics-react-native';

Apptics.setCrashCustomProperty({ 'screen': 'checkout', 'cart_size': 3 });
```

Force-upload any batched stats immediately instead of waiting for the SDK's own
sync schedule.

```plaintext
Apptics.flush();
```

#### Event Tracking

1. Track the configured event with properties using `addEvent` method.

```plaintext
import { Apptics } from '@zoho_apptics/apptics-react-native';

Apptics.addEvent("eventName", "eventGroupName", {'propKey': 'propValue'})
```

#### Screen Tracking

Use the methods provided to track screen navigation.

By default, native screen will also be tracked. But this behavior can be disabled while initializing Apptics.

```plaintext
import { Apptics } from '@zoho_apptics/apptics-react-native';

// Initialize with automatic native screen tracking disabled
Apptics.init(false);

// Then manually track screens
// call when screen appears
Apptics.screenAttached("screenName")

// call when screen disappears
Apptics.screenDetached("screenName")
```

#### Track User

Ties user-id with other stats (events, screens etc)

**User Id tracking will happen with respect to Tracking Settings. If the tracking settings is "WithoutPII", stats will not be associated with the user id.**

```plaintext
import { Apptics } from '@zoho_apptics/apptics-react-native';

// Set user ID
Apptics.setUser("userid")

// Set user ID with organization ID
Apptics.setUserWithOrgId("userid", "orgid")
```

#### Track User with properties

Include additional attributes to users. These properties help segment users for targetted analysis.

```plaintext
import { Apptics, AppticsUserProperty } from '@zoho_apptics/apptics-react-native';

Apptics.setUser("userid", {
      first_name: 'username',
      source: 'React-Android',
      timeline: 265,
      is_subscribed: true
    });

```
User properties support the below mentioned data types:

String - Text values (e.g, "premium", "mobile")
Number - Numeric values (e.g, 25, 10, 15)
Boolean - True/false values (e.g, true, false)

**Limits:**
- Custom user properties: Upto 30 unique custom properties per project.
- Key length: Maximum 50 characters per property key.
- Value length: Maximum 250 characters per property value.

#### Tracking settings

Apptics offer 7 tracking states to control usage and crash tracking.

1. UsageAndCrashTrackingWithPII
2. UsageAndCrashTrackingWithoutPII
3. OnlyUsageTrackingWithPII
4. OnlyUsageTrackingWithoutPII
5. OnlyCrashTrackingWithPII
6. OnlyCrashTrackingWithoutPII
7. NoTracking

> **UsageAndCrashTrackingWithoutPII** is the default state out of the box.

##### Usage Tracking

Usage tracking generally refers to tracking the Events, APIs, Screens, Sessions.

##### Crash Tracking

Crash tracking is self-explanatory and refers to the tracking of undhandled exceptions.

##### PII

The term PII is used to denote the value you set using the `Apptics.setUser` method.

You can use `setTrackingState` method to change the tracking state.

```plaintext
import { Apptics, TrackingState } from '@zoho_apptics/apptics-react-native';

// to change the tracking settings to track only crash and associate user id with crash.
Apptics.setTrackingState(TrackingState.OnlyCrashTrackingWithPII);

// to get the current tracking state - returns a Promise<TrackingState>
const state = await Apptics.getTrackingState();
```

#### Privacy

```plaintext
import { Apptics } from '@zoho_apptics/apptics-react-native';

// open the Apptics-provided tracking settings screen
Apptics.openPrivacySettings();

// present the privacy review pop-up
Apptics.presentPrivacyReviewPopup();

// Android only - prompt the user about the previous session's crash
Apptics.showLastSessionCrashedPopup();

// check whether a user id is currently set - returns a Promise<boolean>
const loggedIn = await Apptics.isUserLoggedIn();
```

#### In-app version alerts

Version alerts can be configured from Apptics webconsole. Please refer user guide. Use the below snippet to check and show version alert pop-up

```plaintext
import { Apptics, AppticsAppUpdate } from '@zoho_apptics/apptics-react-native';

AppticsAppUpdate.showVersionAlertPopup()
```

Make sure to call Apptics.init before calling showVersionAlertPopup.

Add the below colors to your App theme in main/res/values/styles.xml

```plaintext
<item name="appticsTextColor">#000000</item>
<item name="appticsSecondaryTextColor">#000000</item>
<item name="appticsUpdateActionButtonColor">#FF00FF</item>
<item name="appticsUpdateActionButtonTextColor">#000000</item>
<item name="appticsRemindAndIgnoreActionButtonColor">#FF00FF</item>
```

Check our native SDK theme guide to know more about these color tokens.

**Build your own flow** You can use checkForUpdate method to obtain a map of data as configured in the webconsole, which can be used to build your own UI and flow for in-app version alerts.

```plaintext
import { Apptics, AppticsAppUpdate } from '@zoho_apptics/apptics-react-native';

AppticsAppUpdate.checkForUpdate()
```

- Method returns null, if there is no update configured for this version.

Below are the keys available in map obtained from checkForUpdate method.

```plaintext
 'updateid': The ID corresponding to a specific update configuration.
 'currentversion': The version of the app installed on the device.
 'featureTitle': The title or heading for the version alert.
 'features': Update features or what's new.
 'remindMeLaterText': Localized text for the "Remind Me Later" action.
 'updateNowText': Localized text for the "Update" action.
 'neverAgainText': Localized text for the "Ignore" action.

 The 'option' key determines the type of UI selected for this update in the web console:
 option (1): Flexible update flow.
 option (2): Immediate update flow.
 option (3): Force update flow.
 Read More https://www.zoho.com/apptics/resources/user-guide/in-app-updates.html

 'reminderDays': The number of days before showing the popup again if the user chooses "Remind Me Later." These days can be configured from the web console.

 'forceInDays': A custom store URL to redirect when the user taps "Update/Download." This can also be configured from the web console.

 'alertType': The type of the alert - Android in-app updates / ZAnalytics:

 0: ZAnalytics custom UI alert
 1: ZAnalytics native UI alert
 2: Android in-app updates

 'customStoreUrl': You can redirect this URL to another store.
```

- Send action from your custom built pop-up for Apptics to build stats.

```plaintext
import { Apptics, AppticsAppUpdate } from '@zoho_apptics/apptics-react-native';

// update id, fetched from map returned by checkForUpdate
// actions are defined in UpdateStats Enum
AppticsAppUpdate.sendUpdateStat(update_id, UpdateStats.Impression)
```

#### API Tracking

Track outgoing HTTP calls to see latency, status codes and failure rates for your
app's network requests in the Apptics console.

There are three ways to use it, pick whichever suits your networking setup.

**1. Wrap the global fetch.** Every `fetch` call in your app is tracked, including
calls made by libraries built on top of `fetch`.

```plaintext
import { AppticsApiTracker } from '@zoho_apptics/apptics-react-native';

AppticsApiTracker.enableAutoTracking();

// to restore the original fetch
AppticsApiTracker.disableAutoTracking();

// to check the current status
AppticsApiTracker.isAutoTrackingEnabled();
```

**2. Use a tracked fetch explicitly**, leaving the global `fetch` untouched.

```plaintext
import { AppticsApiTracker } from '@zoho_apptics/apptics-react-native';

const res = await AppticsApiTracker.trackedFetch('https://api.example.com/items', {
  method: 'GET',
});
```

Or build a reusable client to pass into your networking layer.

```plaintext
const apiFetch = AppticsApiTracker.createAppticsHttpClient(fetch);

const res = await apiFetch('https://api.example.com/items');
```

**3. Track manually**, for non-`fetch` clients or when you need control over the
recorded status code and error message.

```plaintext
import { AppticsApiTracker } from '@zoho_apptics/apptics-react-native';

const trackId = await AppticsApiTracker.startApiTracking({
  url: 'https://api.example.com/items',
  method: 'GET',
});

try {
  const res = await doRequest();
  if (trackId) {
    await AppticsApiTracker.endApiTracking({ trackId, statusCode: res.status });
  }
} catch (e) {
  if (trackId) {
    await AppticsApiTracker.endApiTracking({ trackId, errorMessage: e.message });
  }
}
```

`startApiTracking` returns `null` when the URL is excluded or the native SDK
declines to track the call, so always check before calling `endApiTracking`.

**Excluding URLs.** Any URL containing one of these substrings is skipped by all
three modes.

```plaintext
AppticsApiTracker.excludedUrlPatterns.add('/healthcheck');
AppticsApiTracker.excludedUrlPatterns.clear();
```

#### Remote Config

Check our user guides to configure Remote config params and conditions.

Use the below snippet to fetch value for a param.

```plaintext
import { Apptics, AppticsRemoteConfig} from '@zoho_apptics/apptics-react-native';

AppticsRemoteConfig.getStringValue("param_name", false, true).then(function(success: string) {
      console.log(success);
    })
```

getStringValue accepts three params. key - the name of the param configured in web console.

coldFetch - getStringValue has a cache mechanism, which prevents frequent network calls. If coldFetch is enabled, getStringValue fetches from Network ignoring the cache mechanism. However, we allow only 3 calls to network per minute, if this threshold breaks the method will return null or fallback to offline value.

fallbackWithOfflineValue - If enabled, getStringValue will return previously fetched value incase of Network failures.

**Custom condition** You can pass the value for custom conditions using the below snippet.

```plaintext
import { Apptics, AppticsRemoteConfig} from '@zoho_apptics/apptics-react-native';

AppticsRemoteConfig.setCustomCondition("condtionKey", "conditionValue")
```

#### Remote Logger

Remote Logger helps you to receive real time application logs from your app and debug issues remotely. Only send logs to Apptics servers from release builds, logs in debug builds will only be printed on the console.

Remote Logger is disabled by default, use the below snippets to enable/disable or get the current status.

```plaintext
import {Apptics, APLogger, APLogLevel} from '@zoho_apptics/apptics-react-native';

// to enable logger
APLogger.enable();

// to disable logger
APLogger.disable();

// to get the current status
APLogger.isEnabled();
```

You can use the below methods to send logs to Apptics

```plaintext
import {Apptics, APLogger, APLogLevel} from '@zoho_apptics/apptics-react-native';

let prop = {'Plan': 'Premium'};

APLogger.log("log from verbose testing", ["mango", "apple"], prop);
APLogger.debug("log from debug");
APLogger.info("log from info");
APLogger.warn("log from warn");
APLogger.error("log from error");
```

Filename and method name captured will be obfuscated.

#### In-App Feedback

In-app feedback enables you to ask for feedback from your users. App users can then attach and annotate images/screenshots, include logs and diagnostics, or report a bug while sharing a feedback.

##### Show feedback screen

You can explicitly present the feedback screen to users on-demand. Use the below method to present the feedback screen.

```plaintext
import { Apptics, AppticsFeedback } from '@zoho_apptics/apptics-react-native';

AppticsFeedback.openFeedback();

```

##### Show report bug screen

Use the below method to automatically capture the screenshot and present annotation activity for reporting bug.

```plaintext
import { Apptics, AppticsFeedback } from '@zoho_apptics/apptics-react-native';

AppticsFeedback.reportBug();
```

##### Shake For Feedback

The Feedback/report bug prompt will be shown when the user shakes the device with the app in the foreground.

- Use the below method to turn off shake for feedback.

```plaintext
import { Apptics, AppticsFeedback } from '@zoho_apptics/apptics-react-native';

AppticsFeedback.disableShakeForFeedback();
```

- Use the blow method to turn on shake for feedback.

```plaintext
import { Apptics, AppticsFeedback } from '@zoho_apptics/apptics-react-native';

AppticsFeedback.enableShakeForFeedback();
```

##### Send Feedback/Bug Report programmatically

You can also send feedback and report bug without presenting our UI, either silently from background or from your custom Feedback UI.

Use the below method to send Feedback.

```plaintext
AppticsFeedback.sendFeedback(
    feedback: string,
    includeLogs: boolean,
    includeDiagnostics: boolean,
    guestMailId: string | null,
    forceToAnonymous: boolean,
    attachments: [string] | null
  )
```

Sample Snippet to select attachment from file picker and send feedback.

```plaintext

// copying file to cache directory before sending feedback.
const res = await DocumentPicker.pickSingle({
      type: [DocumentPicker.types.allFiles],
      copyTo: 'cachesDirectory',
    });
console.log(res.fileCopyUri);

AppticsFeedback.sendFeedback(
  "Hello World",
  true,
  true,
  null,
  false,
  [res.fileCopyUri]
  );
```

##### Attach logs and diagnostics with Feedback.

Apptics' Feedback toolkit provides the necessary APIs to add logs and diagnostic info detail from anywhere in the app. The files containing these data can be sent by the user while sending feedback.

- Use the below method to write log that will be attached to Feedback.

```plaintext
import { Apptics, AppticsFeedback, LogType } from '@zoho_apptics/apptics-react-native';

AppticsFeedback.writeLog(LogType.Debug, "log message);
```

- A diagnostic info file is a set of key-value pairs, where each pair can be grouped under the given heading. To add diagnostic info, use the below method.

```plaintext
import { Apptics, AppticsFeedback, LogType } from '@zoho_apptics/apptics-react-native';

AppticsFeedback.addDiagnosticsInfo("Heading", "key", "value");
```

##### Push Notification

- [Refer the documentation link for more details on platfrom specific setup](https://www.zoho.com/apptics/resources/SDK/react-native-push-notifications.html)

- Start Push Notification Service

```plaintext
import { AppticsPushMessages } from '@zoho_apptics/apptics-react-native';
AppticsPushMessages.startService();
AppticsPushMessages.registerPushNotification();
```

#### In-App Ratings

Ratings module will be initialized automatically on initializing Apptics. 

Android custom review pop-up will be shown automatically once the criterion are satisfied.

To show play core in-app review pop-up for Android, call showPlayCoreAlert function after initializing Apptics.
```plaintext
import { AppticsInAppRatings } from '@zoho_apptics/apptics-react-native';
AppticsInAppRatings.shouldShowPlayCoreAlertForAndroid()
```

To show the iOS App Store in-app rating pop-up, invoke the showAppStoreRatings method after completing Apptics initialization.
```plaintext
import { AppticsInAppRatings } from '@zoho_apptics/apptics-react-native';
AppticsInAppRatings.showAppStoreRatings()
```

