cordova应用程序_适用于Cordova混合应用程序的Firebase云消息传递集成

cordova应用程序

By t1tan1um

由t1tan1um

This is a basic straight forward walk through regarding how to implement push notification in Android as well as iOS using the cordova plugin for fcm and Google Firebase FCM from scratch. I will be using Ubuntu 16.04 LTS for this, but OS used for development should not matter much.

这是有关如何从头开始使用fcm和Google Firebase FCM的cordova插件在Android和iOS中实现推送通知的基本直通指南。 我将为此使用Ubuntu 16.04 LTS,但用于开发的OS应该没什么大不了的。

针对Cordova混合应用程序的FCM集成 (FCM Integration for Cordova Hybrid Apps)

Android实施 (Android Implementation)

Create an empty folder pushSample

创建一个空文件夹pushSample

cd '/opt/lampp/htdocs'
mkdir pushSample
cd pushSample
cordova create pushSample
cd pushSample
cordova platform add android
cordova plugin add cordova-plugin-FCM

While adding the cordova FCM plugin will show an error :

在添加cordova FCM插件时将显示错误:

Error: cordova-plugin-fcm: You have installed platform android but file 'google-services.json' was not found in your Cordova project root folder.

Note : This is because we have not added the google-services.json file which has to be created in the next following steps.

注意:这是因为我们尚未添加必须在接下来的后续步骤中创建的google-services.json文件。

Next open the google firebase console and Add Project ( basically means create a new project )

接下来打开google firebase控制台并添加Project(基本上意味着创建一个新项目)

Once the project is created click on the Notifications section in the left side panel.

创建项目后,单击左侧面板上的“通知”部分。

Now click on the Android icon to add Android platform support to our project.

现在,单击Android图标将Android平台支持添加到我们的项目中。

In the next popup form fill the details as follows : Android package name : Package name or ID is the unique identifier for an app in the play store. Note that it is a very important value which cannot be changed for an app once it is uploaded to the play store. It will be in reverse domain name syntax : eg hello.pushSample.com will have app id : com.pushSample.hello. Also in the config.xml file in your cordova project set the same app id. For our sample project it will be in : pushSample/pushSample/config.xml eg for me the contents of this file are :

在下一个弹出表单中,填写以下详细信息: Android包名称:包名称或ID是Play商店中应用的唯一标识符。 请注意,这是一个非常重要的值,一旦将其上传到Play商店后就无法更改。 它将采用反向域名语法:例如hello.pushSample.com将具有应用程序ID:com.pushSample.hello。 同样,在您的cordova项目的config.xml文件中设置相同的应用程序ID。 对于我们的示例项目,它将位于:pushSample / pushSample / config.xml,例如,对我而言,此文件的内容为:

<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloCordova</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>

Note the tag

注意标签

<widget id="io.cordova.hellocordova" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

Here the attribute id is the package id which will by default be io.cordova.hellocordova change it to the app ID you have specified in the firebase console. I will be using com.pushSample.hello

在这里,属性ID是程序包ID ,默认情况下为io.cordova.hellocordova,将其更改为您在Firebase控制台中指定的应用程序ID。 我将使用com.pushSample.hello

Next field to be filled in the firebase console popup is :

在Firebase控制台弹出窗口中要填写的下一个字段是:

App nickname (optional) : This can be the same app name which is displayed in the menu for the app, this can also be changed in the config.xml, by default it will be HelloCordova, i will update it to PushSample

应用程序昵称(可选):这可以是与应用程序菜单中显示的应用程序相同的名称,也可以在config.xml中更改,默认情况下为HelloCordova,我将其更新为PushSample

Debug signing certificate SHA-1 (optional) : This is optional please leave it blank.

调试签名证书SHA-1(可选):这是可选的,请将其留空。

Next click on Register App

接下来点击注册应用

Next step is to download the google services json file.

下一步是下载google services json文件。

Click on the Download google-services.json button, which should download the file to your PC.

点击“ 下载google-services.json”按钮,该按钮会将文件下载到您的PC。

Once you get the file paste it in the root folder of your cordova project, in my case :

在您获取文件后,将其粘贴到cordova项目的根文件夹中,以我为例:

/opt/lampp/htdocs/pushSample/pushSample

Next build the project

下一步建立项目

cordova build android

After adding the google-services.json file it should build successfully.

添加google-services.json文件后,它应该可以成功构建。

Next we have to write the client side code for handling push notifications :

接下来,我们必须编写用于处理推送通知的客户端代码:

FCMPlugin.getToken(function(token) {
    //this is the FCM token which can be used
    //to send notification to specific device 
    console.log(token);
    //FCMPlugin.onNotification( onNotificationCallback(data), successCallback(msg), errorCallback(err) )
    //Here you define your application behaviour based on the notification data.
    FCMPlugin.onNotification(function(data) {
        console.log(data);
        //data.wasTapped == true means in Background :  Notification was received on device tray and tapped by the user.
        //data.wasTapped == false means in foreground :  Notification was received in foreground. Maybe the user needs to be notified.
        // if (data.wasTapped) {
        //     //Notification was received on device tray and tapped by the user.
        //     alert(JSON.stringify(data));
        // } else {
        //     //Notification was received in foreground. Maybe the user needs to be notified.
        //     alert(JSON.stringify(data));
        // }
    });
});

The code basically first calls the getToken function to get an FCM token from firebase, then in the callback registers another callback onNotification to handle what happens when a push notification is received.

该代码基本上首先调用getToken函数从firebase获取FCM令牌,然后在回调中注册另一个回调onNotification来处理接收到推送通知时发生的情况。

the onNotification function has a data value which contains the notification data. data.wasTapped indicates whether the notification is sent when the app is in foreground or background, so that we can define separate logic for each case. Now to trigger a sample push notification click on the Notification section in the left side panel, this should now show you the firebase notification composer, showing the list of past notifications sent.

onNotification函数具有一个包含通知数据的数据值。 data.wasTapped指示在应用程序处于前台还是后台时是否发送通知,因此我们可以为每种情况定义单独的逻辑。 现在,要触发示例推送通知,请单击左侧面板中的“通知”部分,这现在将向您显示Firebase通知编写器,并显示已发送的过去通知的列表。

In case you have not sent any push notifications yet. You should see a send your first notification button.

如果您尚未发送任何推送通知。 您应该看到“ 发送第一个通知”按钮。

Note: The Notification Composer will look like this :

注意: Notification Composer将如下所示:

Note While sending push notification using firebase console you need to select app name com.pushSample.hello in my case.

注意在使用Firebase控制台发送推送通知时,您需要选择应用名称com.pushSample.hello

To send the custom application specific data select advance options -> Key value pairs.

要发送特定于定制应用程序的数据,请选择高级选项->键值对。

The data object in the onNotification callback will look as follows

onNotification回调中的数据对象如下所示

{myKey2: "valuefor2", myKey: "valuefor1", wasTapped: false}

Also note while sending push notifications using REST APIs from your app server instead of the firebase notification composer, you have to use the following syntax :

另请注意,从应用服务器而非Firebase通知撰写器使用REST API发送推送通知时,您必须使用以下语法:

//POST: https://fcm.googleapis.com/fcm/send
//HEADER: Content-Type: application/json
//HEADER: Authorization: key=AIzaSy*******************
{
  "notification":{
    "title":"Notification title",
    "body":"Notification body",
    "sound":"default",
    "click_action":"FCM_PLUGIN_ACTIVITY",
    "icon":"fcm_push_icon"
  },
  "data":{
    "param1":"value1",
    "param2":"value2"
  },
    "to":"/topics/topicExample",
    "priority":"high",
    "restricted_package_name":""
}
//sound: optional field if you want sound with the notification
//click_action: must be present with the specified value for Android
//icon: white icon resource name for Android >5.0
//data: put any "param":"value" and retreive them in the JavaScript notification callback
//to: device token or /topic/topicExample
//priority: must be set to "high" for delivering notifications on closed iOS apps
//restricted_package_name: optional field if you want to send only to a restricted app package (i.e: com.myapp.test)

Note : “clickaction”:”FCMPLUGIN_ACTIVITY” field is very important as not mentioning it will not execute the onNotification callback in foreground mode.

注意:“ click action”:“ FCM PLUGIN_ACTIVITY”字段非常重要,因为未提及它将不会在前台模式下执行onNotification回调。

iOS实施 (iOS Implementation)

For the iOS implementation we will require the following things to be generated in the apple developer page. I am using XCODE 8.3

对于iOS实施,我们需要在apple开发人员页面上生成以下内容 我正在使用XCODE 8.3

App ID : com.example.app Apple Push Notification Authentication Key ( APNs Auth Key ) Development Provisioning Profile with Push Notifications Enabled. APNs Certificates

应用程序ID:com.example.app启用了推送通知的Apple推送通知身份验证密钥(APNs Auth Key)开发配置文件。 APNs证书

Also Firebase docs for push notifications is an excellent in depth starting point.

此外, 用于推送通知的Firebase文档在深度上也是一个很好的起点。

Note: You cannot run push notifications in the simulator, you will need an actual device.

注意:您不能在模拟器中运行推送通知,您将需要一台实际的设备。

Lets begin.

让我们开始。

Firstly login to firebase developer’s console, and select an existing project or create a new project, we will be using the same pushSample project. In the project overview add another app with iOS as platform. In the popup that comes up, enter the following details :

首先登录到Firebase开发人员控制台,然后选择一个现有项目或创建一个新项目,我们将使用相同的pushSample项目。 在项目概述中,添加另一个以iOS为平台的应用程序。 在出现的弹出窗口中,输入以下详细信息:

  • Step 1 Bundle id : this is the unique identifier which is used to identify an app in the apple appstore, this should be same as the bundle id you will specify in the config.xml file of the cordova project or the Bundle Id section in xCode. we will use com.pushSample.hello App Name : This is the option identifier nick name, we will be using the same name which will display in the iOS app menu which is PushSample. App Store Id : Leave this blank.

    步骤1 捆绑包ID:这是用于在Apple Appstore中标识应用程序的唯一标识符,该标识符应与您将在cordova项目的config.xml文件或xCode的捆绑包ID部分中指定的捆绑包ID相同。 。 我们将使用com.pushSample.hello 应用程序名称 :这是选项标识符的昵称,我们将使用将在iOS应用程序菜单中显示的相同名称PushSample。 App Store ID :将此留空。

Once you click on register app the iOS app step 2 appears.

单击注册应用程序后,将出现iOS应用程序第2步。

  • Step 2 Here click on the download Googleservice-info.plist button to download the file which we will use in the later steps.

    步骤2在这里单击下载Googleservice-info.plist按钮以下载我们将在以后的步骤中使用的文件。

Step3 and Step 4 we can skip as these will be handled internally by the cordova FCM plugin.

步骤3和步骤4我们可以跳过,因为它们将由cordova FCM插件在内部处理。

Once the iOS app is added to your project Click on the gear icon besides the overview label in the left side panel and select project settings. ( Refer below image. ) . This should by default open the General Tab of your project settings.

将iOS应用添加到项目后,单击左侧面板中概述标签旁边的齿轮图标,然后选择项目设置。 (请参见下图。) 默认情况下,这应该打开项目设置的“常规”选项卡。

Next click on your iOS app in Your Apps -> iOS Apps. In the iOS app details update the App ID Prefix, the value for which you will get in the Apple Member Center under the membership tab.

接下来,在您的应用-> iOS应用中单击您的iOS应用。 在iOS应用程序详细信息中,更新“ 应用程序ID前缀” ,您将在“ Apple成员中心”的“成员资格”选项卡下获取该值。

Now switch to the Cloud Messaging tab -> iOS app configuration section.

现在切换到“ 云消息传递”选项卡->“ iOS应用程序配置”部分。

Here as discussed earlier upload the APNs Auth Key you generated in the Apple member center. Next we do the client side app setup. Create a new folder sampleApp in your development folder, for me it is

如前所述,在这里上传您在Apple会员中心生成的APNs身份验证密钥。 接下来,我们进行客户端应用设置。 在您的开发文件夹中创建一个新文件夹sampleApp,对我来说是

/Volumes/Development/

so the new folder will be

所以新文件夹将是

/Volumes/Development/pushSample
cd /Volumes/Development/pushSample

Create a new cordova project, Note : Use sudo if required

创建一个新的cordova项目, 注意:如果需要请使用sudo

cordova create pushSample
cd pushSample

Now add the latest iOS platform

现在添加最新的iOS平台

sudo cordova platform add ios

Now paste the Googleservice-info.plist file we downloaded earlier in the cordova project root folder, for me it is

现在,将我们先前下载的Googleservice-info.plist文件粘贴到cordova项目根文件夹中,对我来说

/Volumes/Development/pushSample/pushSample

add the cordova fcm plugin.

添加cordova fcm插件。

cordova plugin add cordova-plugin-fcm

Update the default app id and app name with the bundle id we decided earlier while configuring firebase console and the app name.

在配置Firebase控制台和应用程序名称时,使用我们先前确定的捆绑包ID更新默认应用程序ID和应用程序名称。

<widget id="com.pushSample.hello" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>PushSample</name>

At this point the sample code will have an app.js file, which you can modify and add the getToken and onNotification functions same as android. The javascript code is same for both platforms.

此时,示例代码将具有一个app.js文件,您可以对其进行修改并添加与android相同的getToken和onNotification函数。 这两个平台的javascript代码相同。

Next run cordova build command

下一步运行cordova build命令

sudo cordova build ios

Once the cordova build command is successful, open the app in xcode. To do this open the xcode.proj file, which will be located in

一旦cordova build命令成功执行,请在xcode中打开该应用程序。 为此,请打开xcode.proj文件,该文件位于

your_cordova_project/platforms/ios/app_name.xcodeproj

for me it is

对我来说

/Volumes/Development/pushSample/pushSample/platforms/ios/PushSample.xcodeproj

Next enable Push Notifications in the Capabilities Tab of the project.

接下来,在项目的“功能”选项卡中启用“推送通知”。

Connect an actual device and run the app.

连接实际设备并运行该应用程序。

Now trigger the push notification from the firebase notification composer and everything should work…

现在从Firebase通知编写器触发推送通知,一切都应该正常工作…

翻译自: https://www.freecodecamp.org/news/firebase-cloud-messaging-integration-for-cordova-hybrid-apps/

cordova应用程序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值