Mobile
Article
By Charles Muzonzini

Push Notifications in Your Ionic App with OneSignal

By Charles Muzonzini

This article was updated on May 3, 2017, for Angular 4 and Ionic 3.

Introduction to push notifications, what they are, how they work

Push notifications are messages sent from your server to your app’s users. They notify users of new content, even when the user is not using your application. They increase user engagement and retention in your app. An example is the WhatsApp “whistle” that notifies you of new messages received. In this tutorial, we’ll dive into integrating push notifications using OneSignal.

How push notifications work

A push notification is sent from the app server to one of the Push notification platforms for the mobile OS. Apple’s Push Notification Service for iOS and Google Cloud Messaging for Android. These push notification services relay the message to the appropriate devices.

You may be wondering, how does your server & GCM know which device to send the notification to? Your app will include code that registers its unique device token with your server.

Keeping track of these device tokens on your server is tedious. But there are some great services out there to simplify the process. One such service is OneSignal.

Step 1: Install Ionic

To start off with, you need to have Ionic installed on your machine. You install it using the node package manager npm;

If you do not have **npm** installed, follow the instructions in the references section to install it.

## Step 2: Start a new project

Next, start a new ionic project by running either one of the following commands based on your target version of Ionic;

**Ionic 1**

$ ionic start PushDemo sidemenu“`

Ionic 2/3

The above command creates a new project in the current directory. The project folder will be called *‘PushDemo’* and it will use the *sidemenu* template.

$ cd PushDemo && ionic serve –lab“`

The code above navigates into your project folder and opens up your app for testing in a browser window.

Browser preview of your ionic app

Step 3: Register on Google Cloud Messaging (GCM)

Visit the Firebase Console and log into your Google account:

https://firebase.google.com/

Firebase Console Home page

Create a new project, give it a name and enter your country.

Create New Firebase Project

Click the Gear icon in the top left and select Project settings -> CLOUD MESSAGING

API Keys

Take note of the two values highlighted in the image. The Server key, also known as the Google Server API key and the Sender ID, also known as the Google Project Number.

Step 4: Create OneSignal Account

Browse to https://www.onesignal.com and create an account.

OneSignal.com

Confirm your email address and login

OneSignal Dashboard

Click on Add new app and name it whatever you want. I would recommend that you give it the same name as you did your ionic project.

Select your platform

Next, select the platform that you want to configure with OneSignal push notifications. In this tutorial, I will be configuring push notifications for Android.

Enter your Google Server API Key and Google Project Number. These are the details you got from the Firebase console in step 3.

Next, select the target SDK for your app. In our case, we are making an Ionic app so you select, “PhoneGap, Cordova, Ionic, Intel XDK”

OneSignal App ID

Take note of your OneSignal App ID. You will need this when integrating OneSignal into your app code.

Step 5: Integrating OneSignal into your ionic project

Go back to the command line window and from within your project directory run;

This will add the OneSignal plugin to your ionic project. This plugin gives our ionic app an API to access Push notifications. Otherwise, they would be unavailable to hybrid apps.

### Step 5a: Integrating OneSignal into Ionic 1

Next, navigate to your main ```app.js``` file *[project-directory]/www/js/app.js*

![](https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/01/1484738035onesignal-code.png)

Add the following code to your ```$ionicPlatform.ready()``` function as above

// One Signal Push Notification Setup
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
console.log(‘didReceiveRemoteNotificationCallBack: ‘ + JSON.stringify(jsonData));
};

window.plugins.OneSignal.init(““,
{googleProjectNumber: ““},
notificationOpenedCallback);

// Show an alert box if a notification comes in when the user is in your app.
window.plugins.OneSignal.enableInAppAlertNotification(true);

Make sure you enter your **App ID** and **Google Project Number**. Save the file.

### Step 5b: Integrating OneSignal into Ionic 2/3

Navigate to your ```app.component.ts``` file *[project-directory]/src/app/app.component.ts*

![](https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/03/1490609438PushDemo-ion2.png)

Add the following code to your ```this.platform.ready()``` function as above

// Enable to debug issues.
// window[“plugins”].OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});

var notificationOpenedCallback = function(jsonData) {
console.log(‘notificationOpenedCallback: ‘ + JSON.stringify(jsonData));
};

window[“plugins”].OneSignal
.startInit(““, ““)
.handleNotificationOpened(notificationOpenedCallback)
.endInit();

Make sure you enter your **App ID** and **Google Project Number**. Save the file.

That's it! That's all you have to do to integrate the OneSignal code into your Ionic 1 or 2/3 app.

Next, connect your android testing device to your computer via USB cable.

Then compile and install the PushDemo app with the following command:

$ ionic build android && adb install -r /platforms/android/build/outputs/apk/android-debug.apk“`

Check Subscribed Users

Next, run the app on your device so that it registers with the OneSignal servers. Then click Check Subscribed Users.

Step 6: Testing

Click on the pushdemo app

Click new push notification

Create a test notification then click preview. Next, click send.

You will immediately receive the push notification on your device.

Push Notification sent from OneSignal

OneSignal extra features

OneSignal has lots of other great features that you should explore further;

  • Emojis in notifications
  • Scheduled notifications
  • Notification templates
  • Realtime analytics
  • User segments
  • Automatic Messages

OneSignal Analytics

OneSignal Analytics

References

  • Installing npm –
    https://www.sitepoint.com/beginners-guide-node-package-manager/

  • Code repository – https://github.com/chmod-777/pushDemo

  • Ionic Framework Documentation – https://ionicframework.com/docs/

  • OneSignal Documentation – https://documentation.onesignal.com/

  • Great to read this great post from an African. This tells me I can also do something great. Will stay in contact with you

    • Charles Muzonzini

      Indeed you can Oliver! Thanks for the positive comment. Please do connect on LinkedIn

  • Finalweb Tecnico Pc-not La Ser

    excellent and works…. how send push notification from app? example, make a button and click and send message !?

  • Delroy Finesse

    Great post. Any updates for ionic 2?

    • Charles Muzonzini

      Thank you. Yes, I’m working on something for ionic 2. Stay tuned.

      • Delroy Finesse

        Nice. Awaiting with patience, also, do add me on facebook or linkedin, also a fellow African.

    • Charles Muzonzini

      The code is exactly the same for Ionic 2. The only difference is that you add it to your app.ts file instead of app.js.

  • Finalweb Tecnico Pc-not La Ser

    Is it possible to send notifications from the app? Example create a button and click to send a notification all? ionic?

  • christian

    Is it possible to send a notification to a desktop environment? (using ionic serve)

    • No. The OneSignal plugin only works on a real device or on an emulator.

  • Ghst3

    Hi. Why onesignal plugin works in Android real device only if the apk does build in–dev mode. In –prod mode One Signal doens’t work. Thank you

    • Hi. I built the app using `$ionic build android –release` and it works perfectly.

  • Luiz Avila

    Hey man great tutorial, but you seem to be missing some steps specially this

    This will add the OneSignal plugin to your ionic project. This plugin gives our ionic app an API to access Push notifications. Otherwise, they would be unavailable to hybrid apps.

    there is no command to add the plugin anywhere.

    thanks,

    Luiz

  • Hi Rohitha, is your issue resolved now?

Recommended
Sponsors
Get the latest in Mobile, once a week, for free.