# SDK Integration

{% embed url="<https://www.npmjs.com/package/react-native-netmera>" %}

## Step 1: Install React Native <a href="#installation" id="installation"></a>

1. **Install Netmera**

{% tabs %}
{% tab title="Yarn" %}

```
yarn add react-native-netmera
```

{% endtab %}

{% tab title="NPM" %}

```
npm install --save react-native-netmera
```

{% endtab %}
{% endtabs %}

2. **Link Netmera (for React Native versions < 0.60)**

Skip this step if you are using React Native version 0.60 or greater.

```
react-native link react-native-netmera
```

For both native sides (Android & iOS), you don't have to include extra Netmera SDK libraries.

## Step 2: Setup iOS <a href="#setup-ios-part" id="setup-ios-part"></a>

### 1. Create an Apple Push Notification Certificate

1. Log in to [**developer.apple.com**](https://developer.apple.com) with your Apple Developer account.
2. Generate an Apple Push Notification Certificate for your app.
3. Export the certificate using **Keychain Access** on your Mac.
4. Upload the exported certificate to the Netmera panel by navigating to **Developer > Push Backends > iOS** in the left menu.

{% hint style="info" %}
**Bundle IDs should match on your project, certificate and panel:**

Ensure that the certificate you upload to the panel matches the bundle ID of your project. Additionally, set your project's bundle ID in the panel to ensure consistency. The bundle ID of your **project**, the **certificate**, and the one specified in the **panel** must all align.
{% endhint %}

{% hint style="info" %}
**Certificate types:**

* For apps downloaded from the App Store or tested via TestFlight, the certificate type should be set to **"prod"**.
* For apps built directly from Xcode, the certificate type must be set to **"dev"**.

If you have problems sending push notifications when you build from Xcode, verify the certificate type on the **Developer > Push Backends > iOS** page in Panel.
{% endhint %}

#### Creating an APNS .p8 Certificate (Recommended)

{% embed url="<https://youtu.be/dv-5gmaGsAA?si=A4V085fUEWMpTzXi>" %}

#### Creating an APNS .p12 Certificate

{% embed url="<https://youtu.be/R8tva2tpFyU?si=9JPg1b9Rqt6b0ldl>" %}

### 2. Integrate & Initialize Netmera iOS SDK <a href="#initialize-netmera" id="initialize-netmera"></a>

#### Install Pods

Navigate to the iOS folder in your terminal and run:

```
$ pod install
```

#### Initialize Netmera in `AppDelegate`

Netmera iOS SDK must be initialized in the AppDelegate file. Follow the steps based on your project type:

* **For Swift Projects:** Modify your `AppDelegate.swift` file.
* **For Objective-C Projects:** Modify your `AppDelegate.m`  and `AppDelegate.h` files.

{% tabs %}
{% tab title="Swift" %}
Modify your `AppDelegate.swift` file:

```swift
import RNNetmera
import Netmera

@main
class AppDelegate: RCTAppDelegate, UNUserNotificationCenterDelegate, NetmeraPushDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
        }

        // Enable logging (Optional: Set to false in production)
        RNNetmera.logging(true)

        // Initialize Netmera with your API Key
        RNNetmera.initNetmera("<YOUR NETMERA API KEY>") // Replace with your API key
        RNNetmera.setPushDelegate(self)

        // Set App Group Name (Required for rich notifications)
        Netmera.setAppGroupName("<YOUR APP GROUP NAME>") // Replace with your App Group Name

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    // MARK: - Push Notification Handling

    @available(iOS 10.0, *)
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        let userInfo = response.notification.request.content.userInfo
        if response.actionIdentifier == UNNotificationDismissActionIdentifier {
            RNNetmeraRCTEventEmitter.onPushDismiss(["userInfo": userInfo])
        } else if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
            RNNetmeraRCTEventEmitter.onPushOpen(["userInfo": userInfo])
        }
        completionHandler()
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.alert])
        RNNetmeraRCTEventEmitter.onPushReceive(["userInfo": notification.request.content.userInfo])
    }

    override func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {
        RNNetmeraRCTEventEmitter.onPushRegister(["pushToken": deviceToken])
    }
}
```

{% hint style="warning" %}
To obtain your **SDK API Key:**

1. Go to the **Netmera Panel**.
2. Navigate to **Developer > API > SDK API Key**.
3. Copy your **SDK API Key** from this section.

Use this key to replace the `<YOUR NETMERA API KEY>` placeholder in the sample code.
{% endhint %}
{% endtab %}

{% tab title="Objective-C" %}
For projects using Objective-C, update both `AppDelegate.h` and `AppDelegate.m` as follows

**Modify `AppDelegate.h`**

```objectivec
#import <React/RCTBridgeDelegate.h>
#import <UIKit/UIKit.h>
#import <Netmera/Netmera.h>
#import <NetmeraCore/NetmeraPushObject.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate, NetmeraPushDelegate>
@property (nonatomic, strong) UIWindow *window;
@end
```

**Modify `AppDelegate.m`**

```objectivec
#import "AppDelegate.h"
#import <RNNetmera/RNNetmeraRCTEventEmitter.h>
#import <RNNetmera/RNNetmeraUtils.h>
#import <RNNetmera/RNNetmera.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [RNNetmera logging:YES]; // Enable Netmera logs
    [RNNetmera initNetmera:[<YOUR NETMERA API KEY>]]; // Replace with your Netmera API Key
    [RNNetmera requestPushNotificationAuthorization];
    [RNNetmera setPushDelegate:self];
    [Netmera setAppGroupName:<YOUR APP GROUP NAME>]; // Set your app group name
    return YES;
}

// Handle push clicks:
-(void)userNotificationCenter:(UNUserNotificationCenter *)center 
didReceiveNotificationResponse:(UNNotificationResponse *)response 
    withCompletionHandler:(void (^)(void))completionHandler {
    if ([response.actionIdentifier isEqual:UNNotificationDismissActionIdentifier]) {
        [RNNetmeraRCTEventEmitter onPushDismiss:@{@"userInfo" : response.notification.request.content.userInfo}];
    } else if ([response.actionIdentifier isEqual:UNNotificationDefaultActionIdentifier]) {
        [RNNetmeraRCTEventEmitter onPushOpen:@{@"userInfo" : response.notification.request.content.userInfo}];
    }
    completionHandler();
}

// Handle push received in foreground:
-(void)userNotificationCenter:(UNUserNotificationCenter *)center 
       willPresentNotification:(UNNotification *)notification 
    withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    completionHandler(UNNotificationPresentationOptionAlert);
    [RNNetmeraRCTEventEmitter onPushReceive:@{@"userInfo" : notification.request.content.userInfo}];
}

// Handle device token registration:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    if (deviceToken) {
        [RNNetmeraRCTEventEmitter onPushRegister:@{@"pushToken" : deviceToken}];
    }
}
@end

```

{% hint style="warning" %}
To obtain your **SDK API Key:**

1. Go to the **Netmera Panel**.
2. Navigate to **Developer > API > SDK API Key**.
3. Copy your **SDK API Key** from this section.

Use this key to replace the `<YOUR NETMERA API KEY>` placeholder in the sample code.
{% endhint %}
{% endtab %}
{% endtabs %}

#### React Native Push Handling

When triggering `[RNNetmeraRCTEventEmitter onPushReceive]` in `AppDelegate`, the corresponding method is called in React Native:

```objectivec
export const onPushReceive = async (message) => {
    console.log("onPushReceive: ", message);
};
```

### 3. iOS10 Media Push Configuration <a href="#using-ios10-media-push" id="using-ios10-media-push"></a>

1. For versions **3.14.4 and above**, complete the steps found in [media-push](https://user.netmera.com/netmera-developer-guide/platforms/ios/former-ios-objective-c/push-notifications/media-push "mention").
2. Update your `Podfile` by adding the following lines **outside of your target**:

```ruby
pod "Netmera", "X.X.X-WithoutDependency"
pod "Netmera/NotificationServiceExtension", "X.X.X-WithoutDependency"
pod "Netmera/NotificationContentExtension", "X.X.X-WithoutDependency"
```

Replace `X.X.X` with the latest version from the **SDK Versions** page > [changelog](https://user.netmera.com/netmera-developer-guide/platforms/react-native/changelog "mention")

**Sample Project**

{% embed url="<https://github.com/Netmera/Netmera-React-Native-Typescript-Example/blob/main/ios/Podfile>" %}

## Step 3: Setup Android <a href="#setup-android-part" id="setup-android-part"></a>

### 1. Netmera Android Onboarding <a href="#create-a-firebase-cloud-messaging-configuration" id="create-a-firebase-cloud-messaging-configuration"></a>

**In Netmera Panel**:

* Navigate to **Developers** > **Netmera Onboarding**.
* Select **Android** and click **Start** to proceed.

<figure><img src="https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2FoCaSsqlqcymmq5PlPJLp%2FScreenshot%202024-04-18%20at%2012.23.23.png?alt=media&#x26;token=9ccd28c4-fd45-4565-afec-c7106eab2267" alt="" width="563"><figcaption></figcaption></figure>

### 2. Create a Firebase Configuration

Netmera uses Firebase Cloud Messaging (FCM) for delivering push notifications.

1. Go to the [**Firebase Developers Console**](https://console.firebase.google.com/) and create a Firebase project.
2. Generate a new **Private Key** (JSON file) for your project.
3. Upload this file in Netmera Panel > Developers > Netmera Onboarding > Android > Step 2: Create A Firebase Configuration > FCM Service Account Key.

{% @arcade/embed flowId="wWs2Yesf5jfbmH6BBLOc" url="<https://app.arcade.software/share/wWs2Yesf5jfbmH6BBLOc>" %}

### 3. Select a Target SDK <a href="#integrate-sdk" id="integrate-sdk"></a>

Choose the React Native SDK based on your application framework.

<figure><img src="https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2FK57LC7cjp4b9T2aCWiFw%2FScreenshot%202024-04-18%20at%2016.37.20.png?alt=media&#x26;token=2025e5e9-f782-4f14-b595-d65d4eeb9557" alt="" width="563"><figcaption></figcaption></figure>

### 4. Integrate and Initialize **React Native** SDK <a href="#integrate-sdk" id="integrate-sdk"></a>

<figure><img src="https://lh7-us.googleusercontent.com/5bVVUuZBFS3dRDP9UO2_i31L0jF2Obwpwrh9jIULVFCy5avp84ss9Ntu_VPtVEw93p7ZIYbOc4EZBJhG4AiXU_G-UNz7ZOGg0Udsq5mCmASNUxTQlMI4uPHeR5DOjr_3Q7MCH5f-HQaPutsOBkrzPwk" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="warning" %}
**Important Notes:**

* **Do not** use the API key from a **test** **panel** in production.
* **Each panel has a unique API key**, and using the wrong one can result in data misdirection or errors.

**To obtain your SDK API Key:**

1. Go to the Netmera Panel.
2. Navigate to Developer > API > SDK API Key.
3. Copy your SDK API Key from this section.
   {% endhint %}

### 5. Integrate Netmera Android SDK <a href="#gradle-file-confugration" id="gradle-file-confugration"></a>

Netmera Android SDK is available through the **Maven repository**. Add the following configurations to your `build.gradle` file. The `AndroidManifest` and other resource settings are automatically managed by the Android Gradle build tool.

#### Gradle Configuration

1. **Project’s `build.gradle` File**

Add the following to your project-level `build.gradle` file:

```groovy
buildscript {
    repositories {
        google()
        jcenter()
        maven { url 'https://developer.huawei.com/repo/' }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:X.X.X'
        classpath 'com.google.gms:google-services:X.X.X'
        classpath 'com.huawei.agconnect:agcp:X.X.X.X'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com' }
        maven { url 'https://developer.huawei.com/repo/' }
        maven { url "https://release.netmera.com/release/android" }
    }
}
```

2. **App’s `build.gradle` File**

Add the required dependency and plugins to your app-level `build.gradle` file:

```groovy
dependencies {
    implementation 'androidx.core:core:1.X.X'
}
```

3. **At the top of your app’s `build.gradle`, include:**

```groovy
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.huawei.agconnect'
```

{% hint style="info" %}
**Important Note for Obfuscation:**

If your code is obfuscated, there is no need to add any special rules for Netmera. Its functionality is unaffected by code obfuscation.
{% endhint %}

### 6. Initialize Netmera Android SDK <a href="#initialize-netmera-1" id="initialize-netmera-1"></a>

1. In your app, locate or create a class that extends `android.app.Application` and implements `com.facebook.react.ReactApplication`

{% hint style="warning" %}
**If you don’t have a class that extends `android.app.Application`**

1. If you don’t have this class, create one.

2. Then, add it to your `AndroidManifest.xml` file under the `<application>` tag using the `android:name`
   {% endhint %}

3. Inside this class, add the following code to the `onCreate()` method

{% tabs %}
{% tab title="Java" %}

```java
import com.netmera.reactnativesdk.RNNetmera;
import com.netmera.reactnativesdk.RNNetmeraConfiguration;

public class MainApplication extends Application implements ReactApplication {
    @Override
    public void onCreate() {
        ...
        RNNetmeraConfiguration netmeraConfiguration = new RNNetmeraConfiguration.Builder()
            .firebaseSenderId(<YOUR GCM SENDER ID>)
            .huaweiSenderId(<YOUR HMS SENDER ID>)
            .apiKey(<YOUR NETMERA API KEY>)
            .logging(true) // Enables Netmera logs.
            .build(this);

        RNNetmera.initNetmera(netmeraConfiguration);
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
import com.netmera.reactnativesdk.RNNetmera
import com.netmera.reactnativesdk.RNNetmeraConfiguration

class MainApplication : Application(), ReactApplication {
    override fun onCreate() {
        ...
        val netmeraConfiguration = RNNetmeraConfiguration.Builder()
            .firebaseSenderId(<YOUR GCM SENDER ID>)
            .huaweiSenderId(<YOUR HMS SENDER ID>)
            .apiKey(<YOUR NETMERA API KEY>)
            .logging(true) // This enables Netmera logs.
            .build(this)

        RNNetmera.initNetmera(netmeraConfiguration)
    }
}
```

{% endtab %}
{% endtabs %}

## Step 4: Setup React Native&#x20;

### Complete Push Callback Methods

Implement the necessary push notification callback methods in your React Native project in the following page:

[push-callbacks](https://user.netmera.com/netmera-developer-guide/platforms/react-native/push-notifications/push-callbacks "mention")

## Step 5: Netmera SDK Push Notification Permission Methods <a href="#about-android-13-push-notification-permissions" id="about-android-13-push-notification-permissions"></a>

On iOS and Android 13+ devices, a runtime push notification permission request is **required**. You can use the following methods to check users' push notification status and request notification permission.

1. **Request Push Notification Authorization**

```javascript
Netmera.requestPushNotificationAuthorization();
```

{% hint style="info" %}
**Push Enable/Disable User Flow:**

1. **Granting Permission:**
   * The user triggers `requestPushNotificationAuthorization()`, and if they grant permission, a push enable request is sent.

2. **Handling Denial:**
   * If the user denies permission, avoid resending the request immediately (as recommended by Google). Instead, the SDK opens the app's notification settings. The user can grant permission from the settings and return to the app, where a push enable request is sent.

3. **Denying Permission:**
   * If the user triggers `requestPushNotificationAuthorization()` and denies permission, a push disable request is sent.

4. **Reattempt After Denial:**
   * If denied, avoid immediate re-request. The SDK will open the app's notification settings. If the user cancels (presses the back button), a push disable request is sent.
     {% endhint %}

5. **Check Notification Permission Status**

This method allows checking whether the necessary permissions for the application have been obtained.

```java
Netmera.checkNotificationPermission().then(status => {
   //NotificationPermissionStatus.NotDetermined
   //NotificationPermissionStatus.Blocked
   //NotificationPermissionStatus.Denied
   //NotificationPermissionStatus.Granted
 });
```

{% hint style="info" %}
**Responses**

When this method is called, it would return one of the following responses:

1. **NOTDETERMINED**\
   The user has opened the app but hasn't made a decision about notification permissions yet.
2. **GRANTED**\
   The user has granted notification permission, and the app can send notifications.
3. **DENIED**\
   The user has denied permission or has blocked notifications through system settings.
   {% endhint %}

## React Native SDK Integration Complete <a href="#sdk-integration-complete" id="sdk-integration-complete"></a>

React Native SDK integration has been successfully completed, and your devices are now ready to receive the following types of push notifications sent via the Netmera Dashboard:

* **Standard Push Notifications**
* **Interactive Push Notifications**
* **Widgets**
* **Push Notifications with Deeplinks**
