Ionic 2 – Sending push notifications to specific devices (Part 1)

Hi Friends,

Hope you are all well. This post is one of the most requested posts on this site. We’ll see how to send push notifications to specific devices through a program. This is done with the help of device tokens and the cordova fcm plugin.

Let’s get started.

A screencast of this post

The complete code of this post can be found here.

I’ll divide the post into two parts.

1) Part 1 – Ionic 2 app that allows us to login and send a message.

2) Part 2 – Real-time database trigger running on firebase cloud that sends a push notification.

First scaffold out an Ionic 2 application. Then install the cordova-plugin-fcm using the below command.

Okay. Now let’s install firebase and angularfire2.

Generate a login page using the below command.

Now open up app.module.ts file and modify it as shown below.

Next, open up your login.html and include some code as shown below.

Open up login.ts and write the signin function.

We have simply got the username and password from the user and we use it to login into our app.

Open up home.ts file and add the below code.

Let’s break this down.

  1. The FCM Plugin methods are pretty much self-explanatory. They do as their name suggests. The onNotification method  watches for notifications, and displays the notifications in alert.
  2. We simply get the device token of the device that the user uses to login and store it in a pushtokens collection. Then we push a message to the messages collection.
  3. We also have a onTokenRefresh method that jumps into action whenever the device token is refreshed. (Here, we haven’t done anything in that method, but in an ideal scenario you need to store the new token in the pushtokens collection).

Now before we run this app, we need to do a few things.

Open up your firebase console. You should see a screen as shown below.

firepic

Now in this screen click on Add firebase to your android app.

You will see a screen as shown below.

firepic2

From your config.xml copy the widget it and paste it in the package name.

Click on register app and you will see a big blue button called google-service.json.

Click on the button. Once the google-services.json file is downloaded, copy and paste it on to your Ionic project’s main folder.

Run the app on any device now. It should go fine.

I will explain how to make use of this token stored in the collections and send msgs automatically to devices whenever a message is stored in the next post. Stay tuned.

Hope this helped you guys. Share it with someone else and help them too.

Thanks for reading. Peace.. :)

 

Liked it? Take a second to support admin on Patreon!
  • José Martínez

    What happend?, this error:
    Runtime Error
    Uncaught (in promise): ReferenceError: FCMPlugin is not defined ReferenceError: FCMPlugin is not defined at http://localhost:8100/build/main.js:56617:13

    I can not find the error.

    Tx

    • Have you declared the FCMPlugin at the top of the file (below the imports) as declare var FCMPlugin..?

      • Dimitri Podoliev

        Yes, and I’m still getting this error:
        FCMPlugin is not defined

        • Dimitri Podoliev

          Raja, any suggestions? I’m still getting “FCMPlugin is not defined” error.
          Thanks a lot!

          • Andres Umaña

            remove “declare”

  • Diego Brito

    I have done the tutorial several times but adding the fcm plugin and build the app gives this error:

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ‘:processDebugGoogleServices’.
    > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.

    • I presume, you have changed the version no of your gradle in fcm plugin’s gradle file.. ? Also, are you using any other google plugins like auth or ionic-push plugin..? (I was stuck in this error for days., don’t worry we will sort this out)

      • Diego Brito

        Yes, I’m using phonegap-plugin-push too and i changed my gradle file by following this steps:

        https://firebase.google.com/docs/android/setup?hl=es-419

        • when you use both phonegap-plugin-push and fcm plugin it won’t work bro.. You need to stop using phonegap-plugin-push.. (Or you need to install the v2.0 branch of fcm plugin and do several modifications to make it work)

          • Ki Bae

            Hi Raja, Thanks for the tutorial. It is very nice but I have same issue as above.

            Execution failed for task ‘:processDebugGoogleServices’.
            > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com
            .google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0.

            I switched ucs-FCMPlugin.gradle as bellow

            dependencies {
            classpath ‘com.android.tools.build:gradle:2.2.3’
            classpath ‘com.google.gms:google-services:3.0.0’
            }

            apply plugin: com.google.gms.googleservices.GoogleServicesPlugin

            but didn’t work. So I removed android platform and FCM several times. unfortunately still have issue. any idea?
            Thanks,

  • javier cabrera

    Hi, Raja Yogan, Thanks for the guide, i have one problem,all process run with succesfully but not the FCMPlugin.getToken(), the return data is null, i run app for ios.
    You know if getToken run in virtual device o in real device?

    Help me please, regards.

    • Andres Umaña

      Also ‘onNotification()’!

      I get the next errors:

      Cannot read property ‘onNotification’ of undefined
      at SavingsPage.ionViewDidLoad (VM6057 main.js:49183)
      at ViewController._lifecycle (VM6057 main.js:18312)
      at ViewController._didLoad (VM6057 main.js:18185)
      at NavControllerBase._didLoad (VM6057 main.js:47939)
      at t.invoke (VM6056 polyfills.js:3)
      at Object.onInvoke (VM6057 main.js:4575)
      at t.invoke (VM6056 polyfills.js:3)
      at r.run (VM6056 polyfills.js:3)
      at NgZone.run (VM6057 main.js:4443)
      at NavControllerBase._viewAttachToDOM (VM6057 main.js:47587)
      defaultErrorLogger @ VM6057 main.js:1510
      ErrorHandler.handleError @ VM6057 main.js:1570
      IonicErrorHandler.handleError @ VM6057 main.js:154838
      NavControllerBase._didLoad @ VM6057 main.js:47944
      t.invoke @ VM6056 polyfills.js:3
      onInvoke @ VM6057 main.js:4575
      t.invoke @ VM6056 polyfills.js:3
      r.run @ VM6056 polyfills.js:3
      NgZone.run @ VM6057 main.js:4443
      NavControllerBase._viewAttachToDOM @ VM6057 main.js:47587
      NavControllerBase._transition @ VM6057 main.js:47676
      (anonymous) @ VM6057 main.js:47358
      t.invoke @ VM6056 polyfills.js:3
      onInvoke @ VM6057 main.js:4575
      t.invoke @ VM6056 polyfills.js:3
      r.run @ VM6056 polyfills.js:3
      (anonymous) @ VM6056 polyfills.js:3
      t.invokeTask @ VM6056 polyfills.js:3
      onInvokeTask @ VM6057 main.js:4566
      t.invokeTask @ VM6056 polyfills.js:3
      r.runTask @ VM6056 polyfills.js:3
      o @ VM6056 polyfills.js:3
      invoke @ VM6056 polyfills.js:3
      VM6057 main.js:1510 ERROR Error: Uncaught (in promise): TypeError: Cannot read property ‘getToken’ of undefined
      TypeError: Cannot read property ‘getToken’ of undefined
      at VM6057 main.js:49197
      at new t (VM6056 polyfills.js:3)
      at SavingsPage.tokensetup (VM6057 main.js:49196)
      at new SavingsPage (VM6057 main.js:49177)
      at createClass (VM6057 main.js:11321)
      at createDirectiveInstance (VM6057 main.js:11149)
      at createViewNodes (VM6057 main.js:12512)
      at createRootView (VM6057 main.js:12417)
      at callWithDebugContext (VM6057 main.js:13632)
      at Object.debugCreateRootView [as createRootView] (VM6057 main.js:13092)
      at VM6057 main.js:49197
      at new t (VM6056 polyfills.js:3)
      at SavingsPage.tokensetup (VM6057 main.js:49196)
      at new SavingsPage (VM6057 main.js:49177)
      at createClass (VM6057 main.js:11321)
      at createDirectiveInstance (VM6057 main.js:11149)
      at createViewNodes (VM6057 main.js:12512)
      at createRootView (VM6057 main.js:12417)
      at callWithDebugContext (VM6057 main.js:13632)
      at Object.debugCreateRootView [as createRootView] (VM6057 main.js:13092)
      at c (VM6056 polyfills.js:3)
      at c (VM6056 polyfills.js:3)
      at VM6056 polyfills.js:3
      at t.invokeTask (VM6056 polyfills.js:3)
      at Object.onInvokeTask (VM6057 main.js:4566)
      at t.invokeTask (VM6056 polyfills.js:3)
      at r.runTask (VM6056 polyfills.js:3)
      at o (VM6056 polyfills.js:3)
      at XMLHttpRequest.invoke (VM6056 polyfills.js:3)

    • Levan Manas

      i am having a similar error….mines says cannot read ‘getToken’ of type undefined ….