Advertisement
  1. Code
  2. NativeScript
Code

Code a Real-Time App With NativeScript: Push Notifications

by
Difficulty:IntermediateLength:LongLanguages:
This post is part of a series called Code a Real-Time NativeScript App.
Code a Real-Time NativeScript App: Social Login and Firebase

NativeScript is a framework for building cross-platform native mobile apps using XML, CSS, and JavaScript. In this series, we're trying out some of the cool things you can do with a NativeScript app: geolocation and Google Maps integration, SQLite database, Firebase integration, and push notifications. Along the way, we're building a fitness app with real-time capabilities that will use each of these features.

In this tutorial, you'll learn how easy it is to add push notifications to your NativeScript app with the Firebase Cloud Messaging Service.

What You'll Be Creating

Picking up from the previous tutorial, you'll be adding push notifications to the app. A notification will be triggered when the user breaks their current record or when one of their friends takes first place away from them.

Setting Up the Project

If you have followed the previous tutorial on Firebase, you can simply use the same project and build the features that we will be adding in this tutorial. Otherwise, you can create a new project and copy the starter files into your project's app folder.

After that, you also need to install the geolocation, Google Maps, SQLite and Firebase plugins:

Once installed, you need to configure the Google Maps plugin. You can read the complete instructions on how to do this by reading the section on Installing the Google Maps Plugin in the earlier tutorial.

Next, install the fecha library for formatting dates:

After that, you also need to configure the Firebase plugin. Be sure to read the following sections in the previous tutorial so you can get the app running:

  • Running the Project
  • Setting Up a Firebase App
  • Setting Up a Facebook App
  • Installing the Firebase Plugin
  • Configuring Facebook Integration

Since we've already set up the Firebase plugin in the previous post, there's only a little work that needs to be done to set up push notifications.

First, you have to reconfigure the plugin by going inside the node_modules/nativescript-plugin-firebase directory and running npm run config. This time, select both Facebook authentication and Messaging.

Once that's done, open the firebase.nativescript.json file in the root directory of your project, and make sure that messaging is set to true:

Next, open app/App_Resources/Android/AndroidManifest.xml and add the following services inside the <application>. This enables the Firebase messaging service for the app:

Running the Project

You can run the project by executing tns run android. But since this app will build on the geolocation functionality, I recommend that you use a GPS emulator for quickly setting and changing your location. You can read about how to do so in the section on Running the App in the earlier tutorial.

If you get any build errors, you can remove the platform and rerun the app:

Setting Up Firebase Cloud Functions

You'll be using Firebase Cloud Functions to create a server that will send out the push notifications. This Firebase feature is used to run back-end code whenever a specific event happens within Firebase features that you're using—for example, if there's a new data saved in the real-time database, or when there's a newly added user via the Firebase auth service. For this app, you'll be using HTTP Triggers to send push notifications when the mobile app makes a request to a specific endpoint.

To use Firebase Cloud Functions, you first need to install the firebase-tools package globally:

Next, create a new folder that will house the server code. This should be outside your app folder. Inside that folder, install the firebase-functions package:

Once it's installed, log in to Firebase by running firebase login. This opens a new browser tab that allows you to log in with your Google account. Go through the whole process and agree to all permissions being asked.

Once you're logged in, you can now initialize Firebase functions for a specific Firebase project:

This will ask you whether you want to set up a default project or not. Select the Firebase project that you created in the previous tutorial:

setup firebase functions

Next, you will be asked if you want the dependencies installed. Say yes.

Once the dependencies have all been installed, you should see a firebase.json file and a functions folder inside the directory. The file that you'll be working on is the functions/index.js file. Open that file and you'll see the following:

Uncomment the helloWorld function, and you'll get to see HTTP triggers in action.

Run the following to deploy the function to the cloud:

Once the deployment is complete, it should show you the URL where the function has been deployed:

deploy firebase functions

Access that URL from your browser to see the output "Hello from Firebase!"

Adding the Server Code

Now you're ready to add the code for implementing push notifications. First, you'll add the code for the server component, then the code for the app.

Open the functions/index.js file and empty its contents. 

Creating the Firebase Function

Import the Firebase packages that you'll need:

Create the init_push function. Note that the HTTP trigger is called for any request method, so you have to filter for the request method that you want to process. In this case, we only want to process POST requests. We expect the app to submit the id, steps, and friend_ids as the request data. 

Getting the User and Friends Data

Next, query the Firebase database to check if the user ID exists. This serves as a way to secure the endpoint so not just anyone can trigger push notifications. (Of course, a real app should have much better back-end security, so that users can't spoof their own data or the data of somebody else.) 

If the user does exist, query the database again so it returns all the users. Note that Firebase does not currently provide a way to return records based on an array of IDs, so we'll have to filter the relevant data ourselves:

Next, loop through the results returned from Firebase and create a new array that houses the friends_data. Once this is done, sort the array according to the number of steps by each user. The one with the highest number of steps has the first index.

Construct the Notification Payload

Now we're ready to determine who will receive the notification and construct the notification payload. Who is in first place? Is it the current user or one of the user's friends? Since the current user will also have broken their own record when they break the overall record of whoever's in first place, we just need to check if that record has been broken.

Sending the Notification

Finally, send out the notification:

Updating the App Code

Earlier, you set up the app so that it was able to receive push notifications. This time, you'll be adding code so that your app can process those push notifications and display them to the user. 

Receiving Push Notifications

The first thing that you need to do in order to receive push notifications is to update the firebase.init() function to include a listener for receiving the device token:

This function only executes once, so you have to save the token locally using application settings. Later on, this will allow us to get the device token when the user logs in for the first time. If you still remember from the previous tutorial, we're saving the user's data to Firebase the first time they log in.

Next, you can add the listener for when notifications are received. This will display an alert box which uses the title and body of the message as the content:

Saving the Device Token to Firebase

Firebase Cloud Messaging requires the device token when sending out a push notification to a specific device. Since we're already using Firebase, we'll just save the device token along with the user data. For that, you need to edit the code for saving the user's data to include the device token that we got earlier:

Triggering Push Notifications

Push Notifications are triggered when one of two things happens:

  • when the user breaks their current record
  • when one of the user's friends breaks their record and goes to first place

The first one is easy, so there's really no need for additional setup. But for the second one, you need to do a little work. First, you have to edit the code for when the auth state changes. Right after extracting the friend IDs from the Facebook result, you have to save the friend IDs using application settings.

Next, update the code for when the user stops tracking their walk. Right after the code for constructing the user data for updating the user, get the friend IDs from application settings and include it in the object which contains the request data for triggering the push notification.

Make the request to the Firebase Cloud Functions endpoint that you created earlier. Once a success response is returned, only then will the user's data be updated on the Firebase database. 

Testing Push Notifications

You can test the sending of push notifications by first uninstalling the app from the emulator or device. This allows us to properly trigger the function for getting the device token. Be sure to add console.log to output the device token:

When the device token is outputted in the NativeScript console, copy it, click on the Database menu on your Firebase app dashboard, and add it as a device token to all the users of the app. Use device_token as the property name.

To trigger the push notification, you can use curl to make a POST request to the Firebase Function endpoint:

If you don't have curl installed, you can use the Postman App to send the request. Use the following settings for the request:

  • Request method: POST
  • URL: Your Firebase function endpoint
  • Headers Key: Content-type
  • Headers Value: application/json
  • Body: 

Once triggered, you'll see an output similar to the following:

push notification received

If the app isn't currently open, you'll see the notification in the notification area:

push notification outside app

Conclusion

Congratulations! You've finally completed the fitness app. Over the course of four tutorials, you've built a NativeScript app which uses Google maps, SQLite, Firebase Realtime database, and Firebase Cloud Messaging. Now you have a pretty good foundation for building NativeScript apps which use those technologies.

To learn more about NativeScript or other cross-platform mobile technologies, be sure to check out some of our other courses and tutorials here on Envato Tuts+!

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.