Push Notifications in Your Ionic App with OneSignal

Share this article

Push Notifications in Your Ionic App with OneSignal

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://uploads.sitepoint.com/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://uploads.sitepoint.com/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/

Frequently Asked Questions (FAQs) about Push Notifications in Your Ionic App with OneSignal

How do I set up OneSignal in my Ionic application?

Setting up OneSignal in your Ionic application involves a few steps. First, you need to install the OneSignal plugin in your Ionic project using the command ionic cordova plugin add onesignal-cordova-plugin. Next, you need to add OneSignal to your app module by importing it and adding it to the list of providers. Then, you need to initialize OneSignal in your app component. This involves setting your OneSignal App ID and Google Project Number. Finally, you need to handle the received push notifications by subscribing to the handleNotificationReceived and handleNotificationOpened events.

How do I send push notifications using OneSignal?

To send push notifications using OneSignal, you need to use the OneSignal dashboard. First, log in to your OneSignal account and navigate to the dashboard. Then, click on ‘New Push’ and fill in the details of the notification you want to send. You can specify the title, message, and additional data. You can also choose to send the notification immediately or schedule it for a later time. Once you’re done, click on ‘Confirm’ to send the notification.

How do I handle push notifications in my Ionic app?

Handling push notifications in your Ionic app involves subscribing to the handleNotificationReceived and handleNotificationOpened events. The handleNotificationReceived event is triggered when a push notification is received while the app is in the foreground. The handleNotificationOpened event is triggered when a push notification is opened. You can use these events to perform actions based on the received notification.

How do I customize the appearance of push notifications?

You can customize the appearance of push notifications using the OneSignal dashboard. When creating a new push notification, you can specify the title, message, and additional data. You can also choose to include an image or a sound with the notification. Additionally, you can customize the notification’s appearance on different platforms by using platform-specific options.

How do I test push notifications in my Ionic app?

To test push notifications in your Ionic app, you can use the OneSignal dashboard to send test notifications. First, make sure your device is subscribed to receive notifications. Then, go to the OneSignal dashboard and click on ‘New Push’. Fill in the details of the notification you want to send and click on ‘Confirm’. The notification should appear on your device shortly.

How do I troubleshoot issues with push notifications?

If you’re having issues with push notifications, there are several things you can check. First, make sure your device is subscribed to receive notifications. You can check this in the OneSignal dashboard. Second, make sure you’ve correctly set up OneSignal in your Ionic app. This includes installing the OneSignal plugin, adding OneSignal to your app module, and initializing OneSignal in your app component. If you’re still having issues, you can check the OneSignal documentation or contact their support team for help.

How do I unsubscribe from push notifications?

To unsubscribe from push notifications, you can use the setSubscription method provided by OneSignal. This method takes a boolean parameter that indicates whether the device should be subscribed to receive notifications. To unsubscribe, you can call this method with the parameter set to false.

How do I use OneSignal with Capacitor?

To use OneSignal with Capacitor, you need to install the OneSignal Capacitor plugin using the command npm install @capacitor-community/onesignal. Then, you need to initialize OneSignal in your app component. This involves setting your OneSignal App ID and Google Project Number. Finally, you need to handle the received push notifications by subscribing to the handleNotificationReceived and handleNotificationOpened events.

How do I use OneSignal with React?

To use OneSignal with React, you need to install the OneSignal React Native SDK using the command npm install react-native-onesignal. Then, you need to initialize OneSignal in your app component. This involves setting your OneSignal App ID and Google Project Number. Finally, you need to handle the received push notifications by subscribing to the handleNotificationReceived and handleNotificationOpened events.

How do I use OneSignal with Android?

To use OneSignal with Android, you need to install the OneSignal Android SDK using the command implementation 'com.onesignal:OneSignal:[4.0.0, 4.99.99]'. Then, you need to initialize OneSignal in your app component. This involves setting your OneSignal App ID and Google Project Number. Finally, you need to handle the received push notifications by subscribing to the handleNotificationReceived and handleNotificationOpened events.

Charles MuzonziniCharles Muzonzini
View Author

Charles Muzonzini is a Mobile App Developer specializing in cross-platform development using the Ionic Framework. He runs a Digital Agency, webgems and he writes mobile app development tutorials at Sitepoint.com and his developer blog, Muzonzini on Mobile. He is also the co-organizer of the Harare WordPress Meetup.

ArielEionicpush notifications
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form