- Version: 1.8.14
- GitHub:
- NPM: https://www.npmjs.com/package/%40pluggableai%2Fsmartpush-sdk
- Downloads:
- Last Day: 0
- Last Week: 0
- Last Month: 0
@pluggableai/smartpush-sdk
Pluggable's Smartpush Plugin for NativeScript apps
npm install @pluggableai/smartpush-sdk
Pre-conditions [Integrate with FCM]
Before using this plugin you should guarantee that your app already integrates with NativeScript Firebase and then with Firebase Cloud Messaging (FCM). The steps are quite easy to follow.
- Install the
@nativescript/firebase-core
plugin (a plugin to initialize FirebaseApp in your app) by running the following command in the root directory of your project (this plugin must be installed before using any other Firebase service).
npm install @nativescript/firebase-core
- 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 the nativescript.config.ts file;
- Download the
google-services.json
file and place it inside the project at the following location: /App_Resources/Android/src/google-services.json.
- 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 or inside the nativescript.config.ts file;;
- Download the
GoogleService-Info.plist
file and place it inside the project at the following location: /App_Resources/iOS/GoogleService-Info.plist; - Then, a set of steps are required for you to obtain an auth key
.p8
file (APNs authentication key) to send push notification to Apple devices. If you don't already have an APNs authentication key, make sure to create one in the Apple Developer Member Center. Then, 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 "Apple 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) and click Upload.
- Instantiate Firebase and initialize a default app (for example, in the /app/app.ts file):
import { firebase } from '@nativescript/firebase-core'
const defaultApp = await firebase().initializeApp()
- You can now install the messaging module by running:
npm install @nativescript/firebase-messaging
- Then, add the SDK by importing the
@nativescript/firebase-messaging
module. You should import this module once in your app, ideally in the main file (e.g. app.ts or main.ts).
import '@nativescript/firebase-messaging'
- iOS Setup - iOS requires further configuration before you can start receiving and sending messages through Firebase. Read the documentation and follow the steps on how to setup iOS with Firebase Cloud Messaging.
- Here note that one of the steps of the above tutorial is incomplete. In particular, the one to Allow processing received a background push notification. You should open app/App_Resources/iOS/Info.plist and add the following code at the bottom:
<key>UIBackgroundModes</key>
<array>
<string>processing</string>
<string>fetch</string>
<string>remote-notification</string>
</array>
- You can then rebuild the project by running in the root's terminal:
ns clean
ns build android
ns build ios
- To handle local and clicked notifications you'll also need the shared-notification-delegate plugin:
npm install @nativescript/shared-notification-delegate
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.
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 run:
-
First install the Smartpush Package by running
npm install @pluggableai/smartpush-sdk
in the root of the project; -
This library exposes two methods which can be imported and used like this:
...
import { SmartpushSdk } from '@pluggableai/smartpush-sdk';
...
const defaultApp = async function () {
console.log('defaultApp function started');
await firebase().initializeApp();
// Allows you to always display notifications while the application is in the foreground
// without sending additional parameters/data when sending the push notification
firebase().messaging().showNotificationsWhenInForeground = true
console.log('Firebase Initialized');
}
defaultApp();
// Request user permission
async function requestUserPermission() {
const authStatus = await firebase()
.messaging()
.requestPermission({
ios: {
alert: true
}
})
const enabled =
authStatus === AuthorizationStatus.AUTHORIZED ||
authStatus === AuthorizationStatus.PROVISIONAL
console.log('Authorization status: ', authStatus)
if (enabled) {
const didRegister = await firebase().messaging().registerDeviceForRemoteMessages().then(() => {
// Init Firebase and calling the below methods
setFirebaseInits();
});
}
}
requestUserPermission()
// Register handler to listen for messages
firebase().messaging().onMessage(async remoteMessage => {
console.log('A new FCM message arrived: ' + JSON.stringify(remoteMessage))
const notifData = remoteMessage.data as {[key: string]: string}
const notificationChannelId = "notificationChannelId"
const notificationChannelName = "notificationChannelName"
let pushUUID = SmartpushSdk.pluggableExecute(notificationChannelId, notificationChannelName, notifData)
console.log('[UUID]: ', pushUUID)
})
// What happens when user clicks in a received push
firebase().messaging().onNotificationTap((message) => {
console.log('CLICKED NOTIFICATION: ', message)
SmartpushSdk.pluggableStoreFeedback();
})
// Needed SharedNotificationDelegate to handle local notifications
SharedNotificationDelegate.addObserver({
userNotificationCenterDidReceiveNotificationResponseWithCompletionHandler: (notificationCenter, notification, handler, next) => {
console.log('CLICKED NOTIFICATION:', notificationCenter);
SmartpushSdk.pluggableStoreFeedback();
next();
},
userNotificationCenterWillPresentNotificationWithCompletionHandler: (notificationCenter, notification, handler, next) => {
console.log("Notification received by observer");
handler(UNNotificationPresentationOptions.Alert);
next();
},
});
// Get user token
firebase().messaging().getToken().then(token => {
console.log('User token: ', token)
//saveTokenToDatabase(token)
});
// Listen to user token changes
firebase().messaging().onToken(token => {
console.log('User token changed to: ', token)
//saveTokenToDatabase(token)
});
// Subscribe to specific topic
firebase().messaging().subscribeToTopic('ns_topic').then(() => {
console.log('Subscribed to topic: ns_topic')
});
NOTE: 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.
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 [email protected].
License
Copyright 2023 PLUGGABLE, LDA (aka PluggableAI)
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.