# smartpush-sdk-ionic

> An Ionic plugin for Ionic apps.

Latest version **1.8.5** (published 2024-01-19) · MIT license · 0 weekly downloads

## Install

```sh
npm install smartpush-sdk-ionic
pnpm add smartpush-sdk-ionic
yarn add smartpush-sdk-ionic
bun add smartpush-sdk-ionic
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities.

Warnings: low downloads; large bundle.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.8.5 |
| Published | 2024-01-19 |
| First published | 2023-10-31 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 44.3 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | PluggableAI |
| Maintainers | brunofmf |
| Keywords | capacitor, plugin, native |

## Links

- npm: https://www.npmjs.com/package/smartpush-sdk-ionic
- Repository: https://github.com/pluggableai/smartpush-sdk-ionic
- Homepage: https://github.com/pluggableai/smartpush-sdk-ionic#readme
- Issues: https://github.com/pluggableai/smartpush-sdk-ionic/issues
- npm.io page: https://npm.io/package/smartpush-sdk-ionic

## Dependencies (1)

- [@capacitor/cli](https://npm.io/package/@capacitor/cli.md) ^5.5.1

## Recent versions

- 1.8.5 (latest) — 2024-01-19
- 1.8.5-beta.0 (beta) — 2024-01-19
- 1.8.4 — 2024-01-19
- 1.8.3 — 2023-12-13
- 1.8.2 — 2023-11-12
- 1.8.1 — 2023-10-31

## README

# Pluggable's Smartpush Plugin for Ionic apps

A Ionic plugin for Ionic apps.

## Pre-conditions [Integrate with FCM]

Before using this plugin you should guarantee that your app already integrates with [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) so that your app can receive push notifications.

1. Create a new [Firebase project](https://console.firebase.google.com/);

2. **Android Setup** - a configuration file must be downloaded and added to the project:
  * On the Firebase console, add a new Android application and enter the projects details. The "Android package name" must match the local projects package name which can be found inside of the manifest tag within the _/android/app/src/main/AndroidManifest.xml_ file within the project;
  * Download the `google-services.json` file and place it at the module (app-level) directory of your app.

3. **iOS Setup** - to allow the iOS app to securely connect to the Firebase project, a configuration file must be downloaded and added to the project:
  * On the Firebase console, add a new iOS application and enter your projects details. The "Apple bundle ID" must match your local project bundle ID. The bundle ID can be found within the "General" tab when opening the project with Xcode;
  * Download the `GoogleService-Info.plist` file;
  * Using Xcode, open the projects _/ios/App/{projectName}.xcodeproj_ file (or _/ios/App/{projectName}.xcworkspace_ if using Pods) and right click on the project name and "Add files" to the project. Select the downloaded `GoogleService-Info.plist` file from your computer, and ensure the **Copy items if needed** checkbox is enabled.

4. Still for **iOS**, you must enable the Push Notifications capability. See [Setting Capabilities](https://capacitorjs.com/docs/v3/ios/configuration?_gl=1*1hu0ptw*_ga*OTMwNDg0MDUuMTY5ODc0MzQ5Mg..*_ga_REH9TJF6KF*MTY5ODc2NzI4OS40LjEuMTY5ODc2Nzc3Ni4wLjAuMA..#setting-capabilities) for instructions on how to enable the capability.

5. Additional **iOS Setup** - iOS requires further configuration before you can start receiving and sending messages through Firebase. For instance:
  * You must upload your APNs authentication key to Firebase. If you don't already have an APNs authentication key, make sure to create one in the [Apple Developer Member Center](https://developer.apple.com/membercenter/index.action);
  * Inside your project in the Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab;
  * In APNs authentication key under iOS app configuration, click the Upload button.
  * Browse to the location where you saved your key, select it, and click Open. Add the key ID for the key (available in the [Apple Developer Member Center](https://developer.apple.com/membercenter/index.action);) and click Upload.
  * For further notes, you can check [React-Native iOS with Firebase Cloud Messaging](https://rnfirebase.io/messaging/usage/ios-setup), which is quite illustrative.

### [Cordova's Firebase plugin](https://www.npmjs.com/package/cordova-plugin-firebase-messaging)

If you don't want to implement FCM's logic natively, one possibility is to install [Cordova's Firebase plugin](https://www.npmjs.com/package/cordova-plugin-firebase-messaging) by running:
  ```
  npm install cordova-plugin-firebase-messaging
  npx cap sync
  ```

The [tutorial](https://www.npmjs.com/package/cordova-plugin-firebase-messaging) is quite easy to follow.

### [Ionic's Firebase plugin](https://ionicframework.com/docs/native/push-notifications)

If you want an Ionic plugin, one possible plugin is the **@capacitor/push-notifications** plugin. Even though it has some limitations, a tutorial is available in [Ionic Docs](https://ionicframework.com/docs/native/push-notifications). To do that, on the project's root:

1. Add the **@capacitor/push-notifications** plugin to the project (`npm install @capacitor/push-notifications`) followed by `npx cap sync`;

2. After enabling the Push Notifications capability in iOS, add the following to your app's _AppDelegate.swift_:
  ```
  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
      NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
  }

  func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
      NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
  }
  ```

3. On **Android**, see [Set up a Firebase Cloud Messaging client app on Android](https://firebase.google.com/docs/cloud-messaging/android/client) for additional information.

### Final Notes

**NOTE 1**: Android 13 requires a permission check in order to receive push notifications. You are required to call `checkPermissions()` and `requestPermissions()` accordingly, when targeting SDK 33.

**NOTE 2**: The FCM plugin (**@capacitor/push-notifications**) does not support iOS Silent Push (Remote Notifications). **You must use native code solutions for handling these types of notifications** in order to have full compatibility with Pluggable's Smartpush Plugin - see [Pushing Background Updates to Your App](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app).

**NOTE 3**: The FCM plugin (**@capacitor/push-notifications**) does support data-only notifications, but will NOT call `pushNotificationReceived` if the app has been killed. To handle this scenario, **you will need to create a service that extends `FirebaseMessagingService`**, see [Handling FCM Messages](https://firebase.google.com/docs/cloud-messaging/android/receive).

**NOTE 4**: FCM via APNs **does not work on iOS Simulators**. To receive messages & notifications a real device is required. The same is recommended for Android.

## Smartpush Usage

After configuring your app to integrate with FCM, you are ready to use this plugin to properly engage with your users. To install the plugin just:

1. First install the [Smartpush Package](https://www.npmjs.com/package/smartpush-sdk-ionic) by running in the root of the project:
  ```
  npm install smartpush-sdk-ionic
  npx cap sync
  ```

2. Go to _/android/build.gradle_ and add the following line to the repositories:
  ```
  ...
  repositories {
      google()
      mavenCentral()
  }
  ...
  ```

3. Once the above steps have been completed, you need to update the project's PODs:
  ```
  # iOS apps
  cd ios/App
  pod install --repo-update
  ```

4. **Note that for Android**, to customize the used notification icon just add the desired icon in the Android's drawble folder and name it **ic_push_app_icon**. Otherwise, a default icon, not related to your app, will be used.

5. This library exposes two methods which can be imported and used like this in any `.tsx` file:
  ```
  ...
  import { Smartpush } from 'smartpush-sdk-ionic';
  ...
  ```

  ```
  // In background and foreground handlers that are listening for FCM notifications, add:
  const notificationChannelId = "notificationChannelId"
  const notificationChannelName = "notificationChannelName"
  const notifData = remoteMessage.data as {[key: string]: string}
  let res = await Smartpush.pluggableExecute({notificationChannelId: notificationChannelId, notificationChannelName: notificationChannelName, notificationData: notifData});
  print(res.uuid)

  // ...

  // To store clicked metrics, add:
  await Smartpush.pluggableStoreFeedback();
  ```

6. Considering that you use the **@capacitor/push-notifications** plugin:
  ```
  // Show the notification payload if the app is open on our device
  PushNotifications.addListener('pushNotificationReceived',
      (notification: PushNotificationSchema) => {
          alert('Push received: ' + JSON.stringify(notification));
          const notificationChannelId = "notificationChannelId"
          const notificationChannelName = "notificationChannelName"
          const notifData = notification as {[key: string]: string}
          let res = await Smartpush.pluggableExecute({notificationChannelId: notificationChannelId, notificationChannelName: notificationChannelName, notificationData: notifData});
          print(res.uuid)
      }
  );
  ```

  ```
  // What happens when user clicks in a received push
  PushNotifications.addListener('pushNotificationActionPerformed',
      (notification: ActionPerformed) => {
          alert('Push action performed: ' + JSON.stringify(notification));
          await Smartpush.pluggableStoreFeedback();
      }
  );
  ```

  ```
  // Get user token 
  PushNotifications.addListener('registration',
      (token: Token) => {
          alert('Push registration success, token: ' + token.value);
      }
  );

  // Some issue with our setup and push will not work
  PushNotifications.addListener('registrationError',
      (error: any) => {
          alert('Error on registration: ' + JSON.stringify(error));
      }
  );
  ```

  ```
  // Request push permissions
  // iOS will prompt user and return if they granted permission or not
  // Android will just grant without prompting
  PushNotifications.requestPermissions().then(result => {
      if (result.receive === 'granted') {
          // Register with Apple / Google to receive push via APNS/FCM
          PushNotifications.register();
      } else {
          // Show some error
      }
  });
  ```

**NOTE**: FCM via APNs **does not work on iOS Simulators**. To receive messages & notifications a real device is required. The same is recommended for Android.

## More info

* For full compatibility, attention to the used versions of XCODE, SWIFT and COCOAPODS. Recommended versions are **XCODE=15**, **SWIFT=5.9**, and **COCOAPODS=1.14.2**.

* For more info visit https://pluggableai.xyz/ or give us feedback to info@pluggableai.xyz.

## API

<docgen-index>

* [`pluggableExecute(...)`](#pluggableexecute)
* [`pluggableStoreFeedback()`](#pluggablestorefeedback)

</docgen-index>

<docgen-api>
<!--Update the source file JSDoc comments and rerun docgen to update the docs below-->

### pluggableExecute(...)

```typescript
pluggableExecute(options: { notificationChannelId: string; notificationChannelName: string; notificationData: object; }) => Promise<{ uuid: string; }>
```

| Param         | Type                                                                                                       |
| ------------- | ---------------------------------------------------------------------------------------------------------- |
| **`options`** | <code>{ notificationChannelId: string; notificationChannelName: string; notificationData: object; }</code> |

**Returns:** <code>Promise&lt;{ uuid: string; }&gt;</code>

--------------------


### pluggableStoreFeedback()

```typescript
pluggableStoreFeedback() => Promise<void>
```

--------------------

</docgen-api>

---
_Source: https://npm.io/package/smartpush-sdk-ionic · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
