Integrate OneSignal Push Notifications Into An Ionic 3 Application

We have discussed Getting Started With Ionic 3 With Typescript in my previous post. Today, I am going to show how to integrate OneSignal push notifications into an Ionic 3 application. I have already created an application so that I can integrate OneSignal into my existing application.
 
Step 1 - Installing OneSignal plugin in your application
  • Open your command prompt (Better to run as Administrator)
  • Change your directory to your project location

    Ionic


  • Type this line in your command prompt and press enter. It will install OneSignal Plugin in your application.
    1. ionic cordova plugin add onesignal-cordova-plugin
    2. npm install --save @ionic-native/onesignal   
 Ionic
 
Step 2 - ImportOneSignal plugin in your application 

After Installing the plugin open app.module.ts and import OneSignal Plugin
  1. import { OneSignal } from '@ionic-native/onesignal';  
  2. OneSignal,
 Ionic
 
Step 3 - Generating Google Server API Key

Goto Google Firebase Console and login with your Gmail Account.

Ionic
Click on Add Project 

Ionic
 
Name your project, choose a country, accept the terms, and click on Create Project.

Now, go to settings and click on Project Settings.

Ionic
 
Go to Cloud Messaging tab and mail a note of both the values listed (Do not share these codes with anyone)
  • Server key also known as Google Server API Key
  • sender ID also known as Google Project Number  

    Ionic 
Step 4 - Configure OneSignal Application
  • Go to OneSignal and login with your ID or create a new one if you don't have any existing or you can login with Gmail, Facebook and GitHub. Currently, I am logging with gmail.

    Ionic

  • After logging in successfully add a new App. Type your app name and click on create. 

    Ionic

  • Select platform and click Next. Currently, I am selecting Google Android.

    Ionic

  • There you need to insert Firebase Server Key And Firebase Sender Id. We have already created those ID's from Google Console Firebase. Copy those IDs and paste it here and click on save.

    Ionic

  • Now, you have to choose SDK for your application. We are developing an application using Ionic so that we can choose Phonegap, Cordova, Ionic, Intel SDK and click on Next.

    Ionic

  • There you can find your App ID. Do not share your AppID with anyone. You need to subscribe first to continue so let's pause this step here and let's get back to our code.

    Ionic
Step 5 - Implement OneSignal Push Notification

We are going to register our device for receiving a push notification. First, we will check if Cordova is avaliable or not; that means if the user is using a web browser or real device. Because push notifications will not work in the browser. For this create a common folder under src and create a folder name common and file called is-cordova-avaliable.ts. put this code inside the is-cordova-avaliable.ts file.
  1. export let isCordovaAvailable = () => {  
  2.     if (!(<any>window).cordova) {  
  3.         alert('This is a native feature. Please use a device');  
  4.         return false;  
  5.     }  
  6.     return true;  
  7. };   
Goto app.component.ts under src/app and add those code over there.
  1. import { OneSignal, OSNotificationPayload } from '@ionic-native/onesignal';  
  2. import { isCordovaAvailable } from '../common/is-cordova-available';  
Add OneSignal plugin in constructor.
  1. private oneSignal: OneSignal,  
Add following line of code in app.component.ts.
  1. if (isCordovaAvailable()){  
  2.   this.oneSignal.startInit('oneSignalAppId', 'sender_id');  
  3.     this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);  
  4.     this.oneSignal.handleNotificationReceived().subscribe(data => this.onPushReceived(data.payload));  
  5.     this.oneSignal.handleNotificationOpened().subscribe(data => this.onPushOpened(data.notification.payload));  
  6.     this.oneSignal.endInit();  
  7. }  
Replace 'oneSignalAppId' with your AppId from OneSignal and 'sender_id' with Google Firebase Sender ID.
  • isCordovaAvaliable() Will check if user is using real devices or not. 
  • startInit('oneSignalAppId', 'sender_id') will start the initilization process.
  • handleNotificationReceived() is a method that runs when notification is received. 
  • handleNotificationOpened() is a method that runs when notification is tapped or clicked.  
  • endInit() is required for complete the initilization process. 
Finally, the following line of code will handle the received and opened notification.
  1. private onPushReceived(payload: OSNotificationPayload) {  
  2.     alert('Push recevied:' + payload.body);  
  3. }  
  4.   
  5. private onPushOpened(payload: OSNotificationPayload) {  
  6.     alert('Push opened: ' + payload.body);  
  7. }  
onPushReceived() will alert user when device will receive new push notification on the device.
onPushOpened() will alert user with the notification message once the notification is opened.
 
And finally your app.component.ts code will look like this.
  1. import { Component } from '@angular/core';  
  2. import { Platform } from 'ionic-angular';  
  3. import { StatusBar } from '@ionic-native/status-bar';  
  4. import { SplashScreen } from '@ionic-native/splash-screen';  
  5.   
  6. import { HomePage } from '../pages/home/home';  
  7. import { OneSignal, OSNotificationPayload } from '@ionic-native/onesignal';  
  8. import { isCordovaAvailable } from '../common/is-cordova-available';  
  9. @Component({  
  10.   templateUrl: 'app.html'  
  11. })  
  12. export class MyApp {  
  13.   rootPage:any = HomePage;  
  14.   
  15.   constructor(platform: Platform,   
  16.     statusBar: StatusBar,   
  17.     private oneSignal: OneSignal,  
  18.     splashScreen: SplashScreen) {  
  19.     platform.ready().then(() => {  
  20.       // Okay, so the platform is ready and our plugins are available.  
  21.       // Here you can do any higher level native things you might need.  
  22.       if (isCordovaAvailable()){  
  23.         this.oneSignal.startInit('oneSignalAppId''sender_id');  
  24.         this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);  
  25.         this.oneSignal.handleNotificationReceived().subscribe(data => this.onPushReceived(data.payload));  
  26.         this.oneSignal.handleNotificationOpened().subscribe(data => this.onPushOpened(data.notification.payload));  
  27.         this.oneSignal.endInit();  
  28.       }  
  29.   
  30.   
  31.       statusBar.styleDefault();  
  32.       splashScreen.hide();  
  33.     });  
  34.       
  35.   }  
  36.   private onPushReceived(payload: OSNotificationPayload) {  
  37.     alert('Push recevied:' + payload.body);  
  38.   }  
  39.     
  40.   private onPushOpened(payload: OSNotificationPayload) {  
  41.     alert('Push opened: ' + payload.body);  
  42.   }  
  43. }  
Step 6 - Test/Run

If you have already installed Android SDK in your application then you can run an application in emmulator with this command.
  1. ionic cordova emulate android  
 Or if you want to run this application in real devices with this command.
  1. ionic cordova run android  
Once you run your application you can navigate to OneSignal Tab in your browser and click on Check Subscribed User there you can find your device with success message.

Ionic
 
Now, navigate to OneSignal dashboard and click on messages.
 
Ionic 

After this type your notification Title and Message and click on Confirm button down below and click on Send Message. You can change notification options like: Color, Icon, Lunch Url, Notification sound e.t.c from Options. Now check you device you will get a push notification like this.
 
Ionic 
 
Now, we have successfully implemented OneSignal Notification in our project.

You can find full source code in GitHub repo from here.

#HappyCoding 
Next Recommended Reading Introduction To Ionic Framework