# SDK Integration

{% embed url="<https://pub.dev/packages/netmera_flutter_sdk#-readme-tab->" %}
Flutter Package
{% endembed %}

## Onboarding Checklist: Flutter

Please find the Onboarding Checklist for Swift and Flutter below. Follow the titles in the checklist to ensure you have completed each essential step in your onboarding process with Netmera.

{% file src="<https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2Fr8VSB0QKkbnrYVr8PSfT%2FNetmera%20Mobile%20Technical%20Onboarding%20Checklist%20(Swift%20%26%20Flutter).xlsx?alt=media&token=82dca8c7-1a84-45ee-8a72-2f7a5f6c1429>" %}

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

To use the Netmera Flutter SDK in your project, follow these steps:

1. Add the following lines to your `pubspec.yaml` file under the dependencies section:

```yaml
dependencies:
  netmera_flutter_sdk: ^x.x.x
```

2. Install the package using the command:

```bash
$ flutter pub get
```

No additional Netmera SDK libraries are required for Android or iOS.

## Step 2: 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 Flutter 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%2F3supzfUtafaF3GFgeg2L%2FScreenshot%202024-04-18%20at%2016.37.44.png?alt=media&#x26;token=ab10a219-520e-440c-b27e-b1200f00a465" alt="" width="563"><figcaption></figcaption></figure>

### 4. Integrate and Initialize **Flutter** 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 <a href="#gradle-file-confugration" id="gradle-file-confugration"></a>

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/'}
    }
}
```

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:X.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 <a href="#initialize-netmera-1" id="initialize-netmera-1"></a>

1. **Create the Application Class (Java)**

* Create an application class that extends `FlutterApplication`.
* Replace `<YOUR GCM SENDER ID>`, `<YOUR HMS SENDER ID>`, and `<YOUR NETMERA API KEY>` with your actual values.

```java
public class NMApp extends FlutterApplication {

    @Override
    public void onCreate() {
        super.onCreate();
        FNetmeraConfiguration fNetmeraConfiguration = new FNetmeraConfiguration.Builder()
            .firebaseSenderId(<YOUR GCM SENDER ID>)
            .huaweiSenderId(<YOUR HMS SENDER ID>)
            .apiKey(<YOUR NETMERA API KEY>)
            .logging(true) // Enable Netmera logs.
            .build(this);
        FNetmera.initNetmera(fNetmeraConfiguration); 
    }
}
```

2. **Set Up Event Handlers in Dart**

Inside your Dart class, add the following code to set up event handlers for push notifications.

```dart
void main() {
  initBroadcastReceiver();
  runApp(MyApp());
}

void _onPushRegister(Map<dynamic, dynamic> bundle) async {
  print("onPushRegister: $bundle");
}

void _onPushReceive(Map<dynamic, dynamic> bundle) async {
  print("onPushReceive: $bundle");
}

void _onPushDismiss(Map<dynamic, dynamic> bundle) async {
  print("onPushDismiss: $bundle");
}

void _onPushOpen(Map<dynamic, dynamic> bundle) async {
  print("onPushOpen: $bundle");
}

void _onPushButtonClicked(Map<dynamic, dynamic> bundle) async {
  print("onPushButtonClicked: $bundle");
}

void _onCarouselObjectSelected(Map<dynamic, dynamic> bundle) async {
  print("onCarouselObjectSelected: $bundle");
}

void initBroadcastReceiver() {
  NetmeraPushBroadcastReceiver receiver = new NetmeraPushBroadcastReceiver();
  receiver.initialize(
    onPushRegister: _onPushRegister,
    onPushReceive: _onPushReceive,
    onPushDismiss: _onPushDismiss,
    onPushOpen: _onPushOpen,
    onPushButtonClicked: _onPushButtonClicked,
    onCarouselObjectSelected: _onCarouselObjectSelected
  );
}
```

### 7. Android 13 Push Notification Permissions <a href="#about-android-13-push-notification-permissions" id="about-android-13-push-notification-permissions"></a>

Android 13 introduced significant changes to how push notification permissions are handled.

* **Increased User Control:** Apps targeting **API Level 33 and above** now have more control over when and how they request push notification permissions. This allows for a more user-friendly and context-aware permission request experience.
* **Automatic Permission Requests for Older Apps:** For apps targeting **API Level 32 and below** running on Android 13, the system automatically prompts the user for push notification permission when the app creates its first notification channel.

**Impact on Netmera SDK Users:**

The Netmera SDK initializes and creates notification channels during the app's startup. Consequently:

* **On Android 13:** For apps targeting API Level 32 and below, this initialization process will trigger the automatic system prompt for push notification permission.
* **On Android 12 and below:** The system generally assumes push notification permission has already been granted.

{% hint style="success" %}
If you initialize the Netmera SDK at app startup (which is recommended), the system will automatically request push notification permissions on Android 13 devices for apps targeting API Level 32 and below. For devices running Android 12 or earlier, the system assumes permission is already granted.
{% endhint %}

#### Push Permission Methods in Netmera SDK

For Android apps targeting API Level 33, the Netmera SDK provides two key methods to handle notification permissions:

1. **Requesting Notification Permissions**

```dart
 Netmera.requestPushNotificationAuthorization();
```

Use this method to request notification permissions from the user. Call this method when you need to prompt the user for permissions at any time.

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

1. **Granting Permission:**
   * The user triggers `requestNotificationPermissions()`, 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 `requestNotificationPermissions()` 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. **Checking Notification Status**

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

```dart
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 %}

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

{% embed url="<https://www.veed.io/view/89de9c71-ecc3-4238-bc41-1f44ffafc783?panel=share>" %}

### 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>" %}

**Install Pods**

1. Navigate to the iOS folder in your terminal and run the following command to install the required pods:

```swift
$ pod install
```

**Swift Configuration**

If you're using Swift, add the following imports in your `Runner-Bridging-Header.h` file:

```swift
#import "FNetmera.h"
#import "FNetmeraService.h"
#import "NetmeraFlutterSdkPlugin.h"
```

### 3. **Initialize** Netmera <a href="#integrate-sdk-into-your-project" id="integrate-sdk-into-your-project"></a>

To enable message sending from iOS to Dart, configure your `AppDelegate` class as follows:

```swift
import UIKit
import Flutter

// This function is needed for sending messages to the Dart side (Setting the callback function).
func registerPlugins(registry: FlutterPluginRegistry) {
    GeneratedPluginRegistrant.register(with: registry)
};

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, UNUserNotificationCenterDelegate, NetmeraPushDelegate {

    override func application(_ application: UIApplication,
                didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        GeneratedPluginRegistrant.register(with: self)

        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
        } else {
            // Fallback for earlier iOS versions
        }

        // Trigger onPushReceive when the app is killed and a push notification is clicked
        if let notification = launchOptions?[.remoteNotification] {
            FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict: ["userInfo": notification])
        }

        // This function is needed for sending messages to the Dart side.
        NetmeraFlutterSdkPlugin.setPluginRegistrantCallback(registerPlugins)

        FNetmera.logging(true) // Enable Netmera logging
        FNetmera.initNetmera("<YOUR-NETMERA-KEY>") // Initialize Netmera
        FNetmera.setPushDelegate(self)
        Netmera.setAppGroupName(<YOUR-APP-GROUP-NAME>) // Set app group name

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

    // Handle registration for push notifications
    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FNetmeraService.handleWork(ON_PUSH_REGISTER, dict: ["pushToken": deviceToken])
    }

    // Handle receiving remote notifications
    override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict: ["userInfo": userInfo])
    }

    // Handle foreground push notifications (iOS 10+)
    @available(iOS 10.0, *)
    override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([UNNotificationPresentationOptions.alert])

        if UIApplication.shared.applicationState == .active {
            FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict: ["userInfo": notification.request.content.userInfo])
        } else {
            FNetmeraService.handleWork(ON_PUSH_RECEIVE_BACKGROUND, dict: ["userInfo": notification.request.content.userInfo])
        }
    }
}
```

{% 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-KEY>")` placeholder in the sample code.
{% endhint %}

#### Triggering Dart Method

When you trigger `FNetmeraService.handleWork(ON_PUSH_RECEIVE, dict: ["userInfo": userInfo])` in `AppDelegate`, the following Dart method will be triggered:

<pre class="language-dart"><code class="lang-dart">void _onPushReceive(Map&#x3C;dynamic, dynamic> bundle) async {
<strong>  print("onPushReceive: $bundle");
</strong>}
</code></pre>

This ensures that push notifications from iOS are correctly handled and passed to your Dart code.

### 4. Request Push Notification Authorization

In Flutter applications targeting iOS, it is necessary to request notification permissions. To request notification permissions on iOS, add the following code to your Flutter app:

```swift
 if (Platform.isIOS) {
      Netmera.requestPushNotificationAuthorization();
    }
```

#### Example Project

For a practical example, check out the [**Netmera Flutter Example Project**](https://github.com/Netmera/Netmera-Flutter-Example/blob/master/lib/main.dart) on GitHub, which shows how to integrate the Flutter SDK and request notification authorization on iOS.

### 5. Configure Xcode Push Notifications Settings <a href="#enable-push-notifications" id="enable-push-notifications"></a>

1. Open your project in Xcode.
2. Navigate to **Signing & Capabilities**.
3. Click **+ Capability** and select **Push Notifications**.

<figure><img src="https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2FavHqs0nhHH5ZozeMP10B%2Fimage.png?alt=media&#x26;token=4b4a2723-38b1-4590-839c-eb860c2d5fee" alt=""><figcaption></figcaption></figure>

### Email Subscription Preferences (Optional)

Use the following methods to manage email subscription preferences in the Netmera SDK:

* **Check if email subscription is allowed:**

  ```dart
  Netmera.isAllowedEmailSubscription()
  ```
* **Set email subscription preference:**

  ```dart
  Netmera.setAllowedEmailSubscription(true);  // Allow subscriptions
  Netmera.setAllowedEmailSubscription(false); // Disallow subscriptions
  ```

### iOS 10 Media Push

For detailed instructions on using iOS 10 Media Push, refer to the specific documentation > [push-notifications](https://user.netmera.com/netmera-developer-guide/platforms/ios/former-ios-objective-c/push-notifications "mention").

## Step 4. Calling Dart Methods <a href="#calling-dart-methods" id="calling-dart-methods"></a>

**onPrem Configuration**

If you're using an **onPrem** setup, you need to set the base URL for Netmera. You can do this using the following method. This will configure the base URL for your on-premise Netmera setup.

```dart
Netmera.setBaseUrl("<YOUR_BASE_URL>");
```

For further details, refer to the documentation for more information.

{% embed url="<https://pub.dev/packages/netmera_flutter_sdk#-readme-tab->" %}

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

Flutter 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**
