search
HomeCMS TutorialWordPressDeveloping real-time applications with NativeScript: implementing push notifications

NativeScript is a framework for building cross-platform native mobile applications using XML, CSS, and JavaScript. In this series, we'll try some of the cool things you can do with NativeScript apps: geolocation and Google Maps integration, SQLite databases, Firebase integration, and push notifications. In the process, we are building a fitness app with real-time features that will be used by the app.

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

What you will create

Continuing from the previous tutorial, you will add push notifications to your app. Notifications will be triggered when a user breaks the current record or when one of their friends takes first place instead of them.

Setting project

If you have followed the previous Firebase tutorial, just use the same project and build the functionality we will add in this tutorial. Otherwise, you can create a new project and copy the starting files into the project's application folder.

tns create fitApp --appid "com.yourname.fitApp"

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

tns plugin add nativescript-geolocation
tns plugin add nativescript-google-maps-sdk
tns plugin add nativescript-sqlite
tns plugin add nativescript-plugin-firebase

After installation, you need to configure the Google Maps plugin. You can read the Installing the Google Maps Plugin section of the previous tutorial for full instructions on how to do this.

Next, install the fecha library for formatting dates:

npm install --save fecha

After that, you also need to configure the Firebase plugin. Be sure to read the following section from the previous tutorial so you can run the application:

  • Run the project
  • Set up Firebase App
  • Set up Facebook App
  • Install Firebase plugin
  • Configuring Facebook Integration

Since we already set up the Firebase plugin in the previous article, there is only a small amount of work to be done to set up push notifications.

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

When finished, open the firebase.nativescript.json file in the project root directory and make sure messaging is set to true:

{
    "using_ios": false,
    "using_android": true,
    "remote_config": false,
    "messaging": true,
    "crash_reporting": false,
    "storage": false,
    "facebook_auth": true,
    "google_auth": false,
    "admob": false,
    "invites": false
}

Next, open app/App_Resources/Android/AndroidManifest.xml and add the following services in <application></application>. This will enable Firebase Messaging for the app:

<application ...>

<service android:name="org.nativescript.plugins.firebase.MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>
<service android:name="org.nativescript.plugins.firebase.MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

</application>

Run the project

You can run the project by executing tns run android. But since this app will be built on geolocation functionality, I recommend using a GPS emulator to quickly set and change your location. You can learn how to do this in the Running the App section of the previous tutorial.

If you encounter any build errors, you can remove the platform and re-run the application:

tns platform remove android
tns run android

Set up Firebase Cloud Function

You will use Firebase Cloud Functions to create a server for sending push notifications. This Firebase feature is used to run backend code when specific events occur within the Firebase feature you are using - for example, if new data is saved in the live database, or through the Firebase Authentication service. For this app, you'll use 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:

npm install -g firebase-tools

Next, create a new folder to hold the server code. This should be outside your application folder. In that folder, install the firebase-functions package:

npm install firebase-functions@latest --save

After the installation is complete, log in to Firebase by running firebase login. This will open a new browser tab allowing you to log in with your Google Account. Complete the entire process and agree to all requested permissions.

After logging in, you can now initialize Firebase functions for a specific Firebase project:

firebase init functions

This will ask you if you want to set a default project. Select the Firebase project you created in the previous tutorial:

使用 NativeScript 开发实时应用程序:实现推送通知

Next, you will be asked if you want to install dependencies. Said to be.

After all dependencies are installed, you should see a firebase.json file and a functions folder in the directory. The file you are trying to process is the functions/index.js file. Open the file and you will see the following:

const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

Uncomment the helloWorld function and you will see the HTTP trigger running.

exports.helloWorld = functions.https.onRequest((request, response) => {
    response.send("Hello from Firebase!");
});

Run the following command to deploy the function to the cloud:

firebase deploy --only functions

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

使用 NativeScript 开发实时应用程序:实现推送通知

从浏览器访问该网址即可查看输出“Hello from Firebase!”

添加服务器代码

现在您已准备好添加用于实现推送通知的代码。首先,您将添加服务器组件的代码,然后添加应用程序的代码。

打开functions/index.js文件并清空其内容。

创建 Firebase 函数

导入您需要的 Firebase 软件包:

const functions = require('firebase-functions'); // for listening to http triggers
const admin = require('firebase-admin'); // for accessing the realtime database
admin.initializeApp(functions.config().firebase); // initialize the Firebase Admin SDK

创建 init_push 函数。请注意,任何请求方法都会调用 HTTP 触发器,因此您必须筛选要处理的请求方法。在本例中,我们只想处理 POST 请求。我们希望应用提交 idstepsfriend_ids 作为请求数据。

exports.init_push = functions.https.onRequest((request, response) => {
    
    if(request.method == 'POST'){

        var id = request.body.id; // ID of the user who made the request (Firebase Auth ID)
        var steps = parseInt(request.body.steps); // latest steps, not recorded yet
        var friend_ids = request.body.friend_ids.split(','); 

        friend_ids.push(id); // also include the ID of the current user

        // next: add code for getting the user and friends data
    }

});

获取用户和好友数据

接下来,查询 Firebase 数据库以检查用户 ID 是否存在。这是保护端点的一种方式,因此并非任何人都可以触发推送通知。 (当然,真正的应用程序应该具有更好的后端安全性,以便用户无法欺骗自己的数据或其他人的数据。)

如果用户确实存在,则再次查询数据库,以便返回所有用户。请注意,Firebase 目前不提供基于 ID 数组返回记录的方法,因此我们必须自己过滤相关数据:

admin.database().ref('/users')
    .orderByChild('id')
    .limitToFirst(1)
    .equalTo(id)
    .once('value').then(snapshot => {
    
    var user_data = snapshot.val();

    if(user_data){
        // get all users from the database
        admin.database().ref('/users')
            .once('value').then(snapshot => {
            // next: add code for getting the current user's data and their friends data
        });
    }
});

接下来,循环遍历从 Firebase 返回的结果并创建一个新数组来容纳 friends_data。完成此操作后,根据每个用户的步数对数组进行排序。步骤数最多的索引为第一个索引。

var friends_data = [];
var current_user_data = null;
var notification_data = {};
var has_notification = false;

var users = snapshot.val();
for(var key in users){
    var user_id = users[key].id;
    
    if(friend_ids.indexOf(user_id) != -1 && id != user_id){ // the current user's friends
        friends_data.push(users[key]);
    }else if(id == user_id){ // the current user
        current_user_data = users[key];
    }
}

// sort in descending order by the number of steps
var sorted_friends_data = friends_data.sort(function(a, b) {
    return b.steps - a.steps;
}); 

// next: add code for constructing the notification payload

构造通知负载

现在我们准备好确定谁将接收通知并构建通知负载。谁是第一名?是当前用户还是用户的朋友之一?由于当前用户在打破第一名的总记录时也打破了自己的记录,因此我们只需要检查该记录是否已被打破。

if(steps > sorted_friends_data[0].steps){
    // notify friend who was overtaken
    var diff_steps = steps - sorted_friends_data[0].steps;
    notification_data = {
        payload: {
            title: 'One of your friends beat your record',
            body: 'Too bad, your friend ' + current_user_data.user_name + ' just overtook you by ' + diff_steps + ' steps'
        },
        device_token: sorted_friends_data[0].device_token
    };
    has_notification = true;
    
}else if(steps > current_user_data.steps){
    // notify current user
    var diff_steps = steps - current_user_data.steps;
    notification_data = {
        payload: {
            title: 'You beat your record!',
            body: 'Congrats! You beat your current record by ' + diff_steps + ' steps!' 
        },
        device_token: current_user_data.device_token
    };
    has_notification = true;
}

// next: add code for sending push notification

发送通知

最后发出通知:

if(has_notification){
    
    var payload = {
      notification: notification_data.payload
    };
    
    // send push notification
    admin.messaging().sendToDevice(notification_data.device_token, payload).then(function(res) {
        
        response.send(JSON.stringify({'has_notification': true})); // inform the app that a notification was sent
    })
    .catch(function(error) {
        response.send(JSON.stringify(error)); // send the push notification error to the app
    });

}else{
    response.send(JSON.stringify({'has_notification': false})); // inform the app that a notification was not sent
}

更新应用代码

之前,您设置了应用程序,以便它能够接收推送通知。这次,您将添加代码,以便您的应用程序可以处理这些推送通知并将其显示给用户。

接收推送通知

为了接收推送通知,您需要做的第一件事是更新 firebase.init() 函数以包含用于接收设备令牌的侦听器:

onPushTokenReceivedCallback: function(token) {
    // temporarily save it to application settings until such time that 
    // the user logs in for the first time
    applicationSettings.setString('device_token', token);
},

此函数仅执行一次,因此您必须使用应用程序设置在本地保存令牌。稍后,这将使我们能够在用户首次登录时获取设备令牌。如果您还记得上一教程,我们会在用户首次登录时将其数据保存到 Firebase。

接下来,您可以添加接收通知时的侦听器。这将显示一个警告框,其中使用消息的标题和正文作为内容:

onMessageReceivedCallback: function(message) {
    dialogs.alert({
        title: message.title,
        message: message.body,
        okButtonText: "ok"
    });
},

将设备令牌保存到 Firebase

Firebase Cloud Messaging 在向特定设备发送推送通知时需要设备令牌。由于我们已经在使用 Firebase,因此我们只需将设备令牌与用户数据一起保存。为此,您需要编辑用于保存用户数据的代码以包含我们之前获得的设备令牌:

if(firebase_result.value == null){ 

    var device_token = applicationSettings.getString('device_token');

    var user_data = {
        'uid': fb_result.uid,
        'user_name': fb_result.name,
        'profile_photo': fb_result.profileImageURL,
        'device_token': device_token 
    };

}

触发推送通知

当发生以下两种情况之一时,将触发推送通知:

  • 当用户打破当前记录时
  • 当用户的一个朋友打破记录并获得第一名时

第一个很简单,因此实际上不需要额外的设置。但对于第二个,你需要做一些工作。首先,您必须编辑身份验证状态更改时的代码。从 Facebook 结果中提取好友 ID 后,您必须使用应用程序设置保存好友 ID。

// extracting the friend IDs from the Facebook result
var friends_ids = r.data.map(function(obj){
    return obj.id;
});

// save the friend IDs
applicationSettings.setString('friends_ids', JSON.stringify(friends_ids));

friends_ids.push(user[user_key].id);

接下来,更新用户何时停止跟踪其步行的代码。在构建更新用户的用户数据的代码之后,从应用程序设置中获取好友 ID,并将其包含在包含触发推送通知的请求数据的对象中。

// construct the user data for updating the user's distance and steps
var user_key = applicationSettings.getString('user_key');
var user = applicationSettings.getString('user');
var user_data = JSON.parse(user);
user_data[user_key].distance = total_distance;
user_data[user_key].steps = total_steps;

// get friend IDs
var friends_ids = JSON.parse(applicationSettings.getString('friends_ids'));

var request_data = {
    'id': user_data[user_key].id,
    'friend_ids': friends_ids.join(','),
    'steps': total_steps
};

向您之前创建的 Firebase Cloud Functions 端点发出请求。一旦返回成功响应,用户的数据才会在 Firebase 数据库上更新。

http.request({ 
    url: "https://us-central1-pushapp-ab621.cloudfunctions.net/init_push", 
    method: "POST",
    headers: { "Content-Type": "application/json" },
    content: JSON.stringify(request_data) 
}).then(function (response) {
   
    var statusCode = response.statusCode;
    if(statusCode == 200){
        // update the user's data on Firebase
        firebase.update(
            '/users',
            user_data
        ); 

    }

}, function (e) {
    console.log('Error occurred while initiating push: ', e);
});

测试推送通知

您可以通过首先从模拟器或设备中卸载应用程序来测试推送通知的发送。这使得我们能够正确触发获取设备令牌的函数。请务必添加 console.log 以输出设备令牌:

onPushTokenReceivedCallback: function(token) {
    applicationSettings.setString('device_token', token);
    console.log('device token: ', device_token); // <-- add this
}

当设备令牌在 NativeScript 控制台中输出时,将其复制,点击 Firebase 应用信息中心上的数据库菜单,并将其作为设备令牌添加给应用的所有用户。使用 device_token 作为属性名称。

要触发推送通知,您可以使用 curl 向 Firebase 函数端点发出 POST 请求:

curl -X POST -H "Content-Type:application/json" YOUR_FIREBASE_FUNCTION_ENDPOINT -d '{"id":"ID OF A FIREBASE USER", "steps":NUMBER_OF_STEPS, "friend_ids":"COMMA,SEPARATED,FIREBASE,USER_IDs"}'

如果您没有安装curl,您可以使用Postman应用发送请求。对请求使用以下设置:

  • 请求方法: POST
  • 网址:您的 Firebase 函数端点
  • 标头键: 内容类型
  • 标头值: application/json
  • 正文: 
{"id":"ID OF A FIREBASE USER", "steps":NUMBER_OF_STEPS, "friend_ids":"COMMA,SEPARATED,FIREBASE,USER_IDs"}

触发后,您将看到类似于以下内容的输出:

使用 NativeScript 开发实时应用程序:实现推送通知

如果应用当前未打开,您将在通知区域中看到通知:

使用 NativeScript 开发实时应用程序:实现推送通知

结论

恭喜!您终于完成了健身应用程序。在四个教程的过程中,您已经构建了一个使用 Google 地图、SQLite、Firebase 实时数据库和 Firebase 云消息传递的 NativeScript 应用。现在您已经为构建使用这些技术的 NativeScript 应用程序奠定了良好的基础。

要了解有关 NativeScript 或其他跨平台移动技术的更多信息,请务必查看我们在 Envato Tuts+ 上的其他一些课程和教程!

The above is the detailed content of Developing real-time applications with NativeScript: implementing push notifications. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Pass PHP Data and Strings to JavaScript in WordPressHow to Pass PHP Data and Strings to JavaScript in WordPressMar 07, 2025 am 09:28 AM

Best Practices for Passing PHP Data to JavaScript: A Comparison of wp_localize_script and wp_add_inline_script Storing data within static strings in your PHP files is a recommended practice. If this data is needed in your JavaScript code, incorporat

How to Embed and Protect PDF Files With a WordPress PluginHow to Embed and Protect PDF Files With a WordPress PluginMar 09, 2025 am 11:08 AM

This guide demonstrates how to embed and protect PDF files within WordPress posts and pages using a WordPress PDF plugin. PDFs offer a user-friendly, universally accessible format for various content, from catalogs to presentations. This method ens

Is WordPress easy for beginners?Is WordPress easy for beginners?Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Why would anyone use WordPress?Why would anyone use WordPress?Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

Is WordPress still free?Is WordPress still free?Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

How much does WordPress cost?How much does WordPress cost?Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Should I use Wix or WordPress?Should I use Wix or WordPress?Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

What is the WordPress good for?What is the WordPress good for?Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),