新增推播通知至您的 Apache Cordova 應用程式Add push notifications to your Apache Cordova app

概觀Overview

在本教學課程中,您會將推播通知新增至 Apache Cordova 快速入門專案,以便在每次插入一筆記錄時,將推播通知傳送至裝置。In this tutorial, you add push notifications to the Apache Cordova quickstart project so that a push notification is sent to the device every time a record is inserted.

如果您未使用下載的快速入門伺服器專案,則需要推播通知擴充套件。If you do not use the downloaded quickstart server project, you need the push notification extension package. 如需詳細資訊,請參閱使用適用於 Mobile Apps 的 .NET 後端伺服器 SDKFor more information, see Work with the .NET back-end server SDK for Mobile Apps.

必要條件Prerequisites

本教學課程假設您擁有以 Visual Studio 2015 開發的 Apache Cordova 應用程式。This tutorial assumes that you have an Apache Cordova application that was developed with Visual Studio 2015. 此裝置應在 Google Android Emulator、Android 裝置、Windows 裝置或 iOS 裝置上執行。This device should run on Google Android Emulator, an Android device, a Windows device, or an iOS device.

若要完成本教學課程,您需要:To complete this tutorial, you need:

設定通知中樞Configure a notification hub

Azure App Service 的 Mobile Apps 使用 Azure 通知中樞來傳送推送,因此您將為行動應用程式設定通知中樞。The Mobile Apps feature of Azure App Service uses Azure Notification Hubs to send pushes, so you will be configuring a notification hub for your mobile app.

  1. Azure 入口網站中,移至 [應用程式服務],然後選取應用程式後端。In the Azure portal, go to App Services, and then select your app back end. 在 [設定] 底下,選取 [推播]。Under Settings, select Push.
  2. 將通知中樞資源新增至應用程式,選取 [連線]。To add a notification hub resource to the app, select Connect. 您可以建立中樞或連線到現有的中樞。You can either create a hub or connect to an existing one.

    設定中樞

現在您已將通知中樞連接到 Mobile Apps 後端專案。Now you have connected a notification hub to your Mobile Apps back-end project. 稍後您要設定此通知中樞,使其連線到平台通知系統 (PNS) 以推播至裝置。Later you configure this notification hub to connect to a platform notification system (PNS) to push to devices.

觀看示範本節步驟的影片Watch a video showing steps in this section.

更新伺服器專案Update the server project

在本節中,您會更新現有 Mobile Apps 後端專案中的程式碼,以在每次新增項目時傳送推播通知。In this section, you update code in your existing Mobile Apps back-end project to send a push notification every time a new item is added. 此程序是由 Azure 通知中樞的範本功能所提供,可啟用跨平台推播。This process is powered by the template feature of Azure Notification Hubs, which enables cross-platform pushes. 各種用戶端會使用範本來註冊推播通知,而單一通用推播即可送達所有的用戶端平台。The various clients are registered for push notifications using templates, and a single universal push can get to all client platforms.

請選擇下列其中一個符合您後端專案類型(—.NET 後端Node.js 後端)的程序。Choose one of the following procedures that matches your back-end project type—either .NET back end or Node.js back end.

.NET 後端專案.NET back-end project

  1. 在 Visual Studio 中,以滑鼠右鍵按一下伺服器專案。In Visual Studio, right-click the server project. 然後選取 [管理 NuGet 套件] 。Then select Manage NuGet Packages. 搜尋 Microsoft.Azure.NotificationHubs,然後選取 [安裝]。Search for Microsoft.Azure.NotificationHubs, and then select Install. 此程序會安裝通知中樞程式庫,以便從後端傳送通知。This process installs the Notification Hubs library for sending notifications from the back end.
  2. 在伺服器專案中,開啟 [控制器]Controllers > [TodoItemController.cs]。In the server project, open Controllers > TodoItemController.cs. 然後新增下列 using 陳述式:Then add the following using statements:

    using System.Collections.Generic;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Azure.Mobile.Server.Config;
    
  3. PostTodoItem 方法中,於呼叫 InsertAsync 之後新增下列程式碼:In the PostTodoItem method, add the following code after the call to InsertAsync:

    // Get the settings for the server project.
    HttpConfiguration config = this.Configuration;
    MobileAppSettingsDictionary settings =
        this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
    
    // Get the Notification Hubs credentials for the mobile app.
    string notificationHubName = settings.NotificationHubName;
    string notificationHubConnection = settings
        .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
    
    // Create a new Notification Hub client.
    NotificationHubClient hub = NotificationHubClient
    .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
    // Send the message so that all template registrations that contain "messageParam"
    // receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
    Dictionary<string,string> templateParams = new Dictionary<string,string>();
    templateParams["messageParam"] = item.Text + " was added to the list.";
    
    try
    {
        // Send the push notification and log the results.
        var result = await hub.SendTemplateNotificationAsync(templateParams);
    
        // Write the success result to the logs.
        config.Services.GetTraceWriter().Info(result.State.ToString());
    }
    catch (System.Exception ex)
    {
        // Write the failure result to the logs.
        config.Services.GetTraceWriter()
            .Error(ex.Message, null, "Push.SendAsync Error");
    }
    

    插入新的項目時,此程序會傳送包含 item.Text 的範本通知。This process sends a template notification that contains the item.Text when a new item is inserted.

  4. 發佈伺服器專案。Republish the server project.

Node.js 後端專案Node.js back-end project

  1. 如果您還沒這麼做,請下載快速入門後端專案或使用 Azure 入口網站中的線上編輯器If you haven't already done so, download the quickstart back-end project, or else use the online editor in the Azure portal.
  2. 在 todoitem.js 中,以下列程式碼取代現有的程式碼:Replace the existing code in todoitem.js with the following code:

    var azureMobileApps = require('azure-mobile-apps'),
    promises = require('azure-mobile-apps/src/utilities/promises'),
    logger = require('azure-mobile-apps/src/logger');
    
    var table = azureMobileApps.table();
    
    table.insert(function (context) {
    // For more information about the Notification Hubs JavaScript SDK,
    // see http://aka.ms/nodejshubs.
    logger.info('Running TodoItem.insert');
    
    // Define the template payload.
    var payload = '{"messageParam": "' + context.item.text + '" }';  
    
    // Execute the insert. The insert returns the results as a promise.
    // Do the push as a post-execute action within the promise flow.
    return context.execute()
        .then(function (results) {
            // Only do the push if configured.
            if (context.push) {
                // Send a template notification.
                context.push.send(null, payload, function (error) {
                    if (error) {
                        logger.error('Error while sending push notification: ', error);
                    } else {
                        logger.info('Push notification sent successfully!');
                    }
                });
            }
            // Don't forget to return the results from the context.execute().
            return results;
        })
        .catch(function (error) {
            logger.error('Error while running context.execute: ', error);
        });
    });
    
    module.exports = table;  
    

    插入新的項目時,此程序會傳送包含 item.Text 的範本通知。This process sends a template notification that contains the item.text when a new item is inserted.

  3. 當您在本機電腦上編輯檔案時,請重新發佈伺服器專案。When you edit the file on your local computer, republish the server project.

修改您的 Cordova 應用程式Modify your Cordova app

若要確保您的 Apache Cordova 應用程式專案能夠處理推播通知,請安裝 Cordova 推播外掛程式,還有平台特定的所有推播服務。To ensure that your Apache Cordova app project is ready to handle push notifications, install the Cordova push plugin plus any platform-specific push services.

更新您的專案中的 Cordova 版本。Update the Cordova version in your project.

如果您的專案使用 6.1.1 版以前的 Apache Cordova,請更新用戶端專案。If your project uses a version of Apache Cordova that's earlier than version 6.1.1, update the client project. 若要更新專案,請採取下列步驟:To update the project, take the following steps:

  • 以滑鼠右鍵按一下 config.xml 開啟設定設計工具。To open the configuration designer, right-click config.xml.
  • 選取 [平台] 索引標籤。Select the Platforms tab.
  • 在 [Cordova CLI] 文字方塊中選取 [6.1.1]。In the Cordova CLI text box, select 6.1.1.
  • 若要更新專案,選取 [建置],然後選取 [建置解決方案]。To update the project, select Build, and then select Build Solution.

安裝推播外掛程式Install the push plugin

Apache Cordova 應用程式原本就不會處理裝置或網路功能。Apache Cordova applications do not natively handle device or network capabilities. 這些功能是由 npm 或 GitHub 上發佈的外掛程式所提供。These capabilities are provided by plugins that are published either on npm or on GitHub. phonegap-plugin-push 外掛程式會處理網路推播通知。The phonegap-plugin-push plugin handles network push notifications.

您可透過下列其中一種方式安裝推播外掛程式:You can install the push plugin in one of the following ways:

從命令提示:From the command-prompt:

執行以下命令:Run the following command:

cordova plugin add phonegap-plugin-push

從 Visual Studio 內:From within Visual Studio:

  1. 在方案總管中開啟 config.xml 檔案。In Solution Explorer, open the config.xml file. 接著,選取 [外掛程式] > [自訂]。Next, select Plugins > Custom. 然後選取 [Git] 作為安裝來源。Then select Git as the installation source.

  2. 輸入 https://github.com/phonegap/phonegap-plugin-push 作為來源。Enter https://github.com/phonegap/phonegap-plugin-push as the source.

    在方案總管中開啟 config.xml 檔案

  3. 選取安裝來源旁邊的箭頭。Select the arrow next to the installation source.

  4. SENDER_ID 中,如果您已經有 Google 開發人員主控台專案的數值專案識別碼,您可以在此將它新增。In SENDER_ID, if you already have a numeric project ID for the Google Developer Console project, you can add it here. 否則,請輸入預留位置值,例如 777777。Otherwise, enter a placeholder value, such as 777777. 如果您是以 Android 為目標,您可以稍後在 config.xml 檔案中更新此值。If you are targeting Android, you can update this value in the config.xml file later.

    注意

    自 2.0.0 版開始,google-services.json 必須安裝在專案的根資料夾中,以設定寄件者識別碼。As of version 2.0.0, google-services.json needs to be installed in the root folder of your project to configure the sender ID. 如需詳細資訊,請參閱安裝文件。For more information, see the installation documentation.

  5. 選取 [新增] 。Select Add.

推撥外掛程式現已安裝。The push plugin is now installed.

安裝裝置外掛程式Install the device plugin

遵循您安裝推播外掛程式時的相同程序。Follow the same procedure you used to install the push plugin. 從核心外掛程式清單中新增裝置外掛程式。Add the Device plugin from the Core plugins list. (選取 [外掛程式] > [核心] 以尋找它。)您需要此外掛程式才能取得平台名稱。(To find it, select Plugins > Core.) You need this plugin to obtain the platform name.

在應用程式啟動時註冊您的裝置Register your device when the application starts

最初,我們包含一些適用於 Android 的最少程式碼。Initially, we include some minimal code for Android. 之後您可以將應用程式修改為在 iOS 或 Windows 10 上執行。Later you can modify the app to run on iOS or Windows 10.

  1. 在登入程序的回呼期間將呼叫新增至 registerForPushNotificationsAdd a call to registerForPushNotifications during the callback for the sign-in process. 或者,您可以在 onDeviceReady 方法底部新增它:Alternatively, you can add it at the bottom of the onDeviceReady method:

    // Log in to the service.
    client.login('google')
        .then(function () {
            // Create a table reference.
            todoItemTable = client.getTable('todoitem');
    
            // Refresh the todoItems.
            refreshDisplay();
    
            // Wire up the UI Event Handler for the Add Item.
            $('#add-item').submit(addItemHandler);
            $('#refresh').on('click', refreshDisplay);
    
                // Added to register for push notifications.
            registerForPushNotifications();
    
        }, handleError);
    

    這個範例示範在成功驗證之後呼叫 registerForPushNotificationsThis example shows calling registerForPushNotifications after authentication succeeds. 您可以依需要經常呼叫 registerForPushNotifications()You can call registerForPushNotifications() as often as is required.

  2. 加入新的 registerForPushNotifications 方法,如下所示︰Add the new registerForPushNotifications method as follows:

    // Register for push notifications. Requires that phonegap-plugin-push be installed.
    var pushRegistration = null;
    function registerForPushNotifications() {
        pushRegistration = PushNotification.init({
            android: { senderID: 'Your_Project_ID' },
            ios: { alert: 'true', badge: 'true', sound: 'true' },
            wns: {}
        });
    
    // Handle the registration event.
    pushRegistration.on('registration', function (data) {
        // Get the native platform of the device.
        var platform = device.platform;
        // Get the handle returned during registration.
        var handle = data.registrationId;
        // Set the device-specific message template.
        if (platform == 'android' || platform == 'Android') {
            // Register for GCM notifications.
            client.push.register('gcm', handle, {
                mytemplate: { body: { data: { message: "{$(messageParam)}" } } }
            });
        } else if (device.platform === 'iOS') {
            // Register for notifications.
            client.push.register('apns', handle, {
                mytemplate: { body: { aps: { alert: "{$(messageParam)}" } } }
            });
        } else if (device.platform === 'windows') {
            // Register for WNS notifications.
            client.push.register('wns', handle, {
                myTemplate: {
                    body: '<toast><visual><binding template="ToastText01"><text id="1">$(messageParam)</text></binding></visual></toast>',
                    headers: { 'X-WNS-Type': 'wns/toast' } }
            });
        }
    });
    
    pushRegistration.on('notification', function (data, d2) {
        alert('Push Received: ' + data.message);
    });
    
    pushRegistration.on('error', handleError);
    }
    
  3. (Android) 在上述程式碼中,從 Google Developer Console 使用應用程式的數字專案識別碼取代 Your_Project_ID(Android) In the preceding code, replace Your_Project_ID with the numeric project ID for your app from the Google Developer Console.

(選擇性) 在 Android 上設定和執行應用程式(Optional) Configure and run the app on Android

完成本節可以為 Android 啟用推播通知。Complete this section to enable push notifications for Android.

啟用 Firebase 雲端傳訊Enable Firebase Cloud Messaging

因為一開始是以 Google Android 平台為目標,所以您必須啟用 Firebase 雲端通訊。Since you are targeting the Google Android platform initially, you must enable Firebase Cloud Messaging.

  1. 登入 Firebase 主控台Sign in to the Firebase console. 建立新的 Firebase 專案 (如果您還沒有 Firebase 專案的話)。Create a new Firebase project if you don't already have one.
  2. 建立專案之後,請選取 [將 Firebase 新增至 Android 應用程式]。After you create your project, select Add Firebase to your Android app. 然後依照所提供的指示執行。Then follow the instructions that are provided. 下載 google-services.json 檔案。Download google-services.json file.

    將 Firebase 新增至 Android 應用程式

  3. 在 Firebase 主控台中,選取您專案的齒輪圖示。In the Firebase console, select the cog for your project. 然後選取 [專案設定]。Then select Project Settings.

    選取專案設定

  4. 選取您專案設定中的 [一般] 索引標籤。Select the General tab in your project settings. 然後下載其中包含伺服器 API 金鑰和用戶端識別碼的 google-services.json 檔案。Then download the google-services.json file that contains the Server API key and Client ID.
  5. 選取專案設定中的 [雲端通訊] 索引標籤,然後複製 [舊版伺服器金鑰] 的值。Select the Cloud Messaging tab in your project settings, and then copy the value of the Legacy server key. 您可使用此值來設定通知中樞存取原則。You use this value to configure the notification hub access policy.

設定行動應用程式後端以使用 FCM 傳送推送要求Configure the Mobile App back end to send push requests using FCM

  1. Azure 入口網站中,選取 [瀏覽全部] > [應用程式服務]。In the Azure portal, select Browse All > App Services. 然後選取您的 Mobile Apps 後端。Then select your Mobile Apps back end.
  2. 在 [設定] 底下,選取 [推播]。Under Settings, select Push. 然後選取 [設定推播通知服務]。Then select Configure push notification services.
  3. 前往 Google (GCM)Go to Google (GCM). 輸入透過 Firebase 主控台取得的 FCM 舊版伺服器金鑰,然後選取 [儲存]。Enter the FCM legacy server key that you obtained from the Firebase console, and then select Save.

您的服務現在已設定為與 Firebase 雲端通訊搭配使用。Your service is now configured to work with Firebase Cloud Messaging.

針對 Android 設定您的 Cordova 應用程式Configure your Cordova app for Android

在 Cordova 應用程式中,開啟 config.xmlIn your Cordova app, open config.xml. 然後從 Google Developer Console 使用應用程式的數字專案識別碼取代 Your_Project_IDThen replace Your_Project_ID with the numeric project ID for your app from the Google Developer Console.

<plugin name="phonegap-plugin-push" version="1.7.1" src="https://github.com/phonegap/phonegap-plugin-push.git">
    <variable name="SENDER_ID" value="Your_Project_ID" />
</plugin>

開啟 index.jsOpen index.js. 然後更新程式碼以使用您的數值專案識別碼。Then update the code to use your numeric project ID.

pushRegistration = PushNotification.init({
    android: { senderID: 'Your_Project_ID' },
    ios: { alert: 'true', badge: 'true', sound: 'true' },
    wns: {}
});

設定 Android 裝置進行 USB 偵錯Configure your Android device for USB debugging

在您可以將應用程式部署到您的 Android 裝置之前,您需要啟用 USB 偵錯。Before you can deploy your application to your Android Device, you need to enable USB debugging. 在您的 Android 手機上執行下列步驟:Take the following steps on your Android phone:

  1. 移至 [設定] > [關於手機]。Go to Settings > About phone. 然後點選 [組建編號],直到啟用開發人員模式為止 (大約七次)。Then tap the Build number until developer mode is enabled (about seven times).
  2. 回到 [設定] > [開發人員選項],啟用 [USB 偵錯]。Back in Settings > Developer Options, enable USB debugging. 然後使用 USB 纜線將您的 Android 手機連接到開發電腦。Then connect your Android phone to your development PC with a USB cable.

我們測試時使用的是執行 Android 6.0 (Marshmallow) 的 Google Nexus 5 X 裝置。We tested this using a Google Nexus 5X device running Android 6.0 (Marshmallow). 不過,這些技術在任何現代化 Android 版本中都是相同的。However, the techniques are common across any modern Android release.

安裝 Google Play 服務Install Google Play Services

推播外掛程式仰賴 Android Google Play 服務來進行推播通知。The push plugin relies on Android Google Play Services for push notifications.

  1. 在 Visual Studio 中,選取 [工具] > [Android] > [Android SDK 管理員]。In Visual Studio, select Tools > Android > Android SDK Manager. 然後展開 [Extras] 資料夾。Then expand the Extras folder. 請檢查適當的方塊,確定已安裝所有下列的 SDK:Check the appropriate boxes to ensure that each of the following SDKs is installed:

    • Android 2.3 或更新版本Android 2.3 or higher
    • Google Repository 版本 27 或更高版本Google Repository revision 27 or higher
    • Google Play 服務 9.0.2 或更高版本Google Play Services 9.0.2 or higher
  2. 選取 [安裝套件]。Select Install Packages. 然後等待安裝完成。Then wait for the installation to finish.

phonegap-plugin-push 安裝文件中列出目前必要的程式庫。The current required libraries are listed in the phonegap-plugin-push installation documentation.

在 Android 上的應用程式中測試推播通知Test push notifications in the app on Android

您現在可以執行應用程式,在 TodoItem 資料表中插入項目,以測試推播通知。You can now test push notifications by running the app and inserting items in the TodoItem table. 只要是使用相同的後端,您可以從相同的裝置或第二部裝置來測試。You can test from the same device or from a second device, as long as you are using the same back end. 以下列方法之一在 Android 平台上測試 Cordova 應用程式︰Test your Cordova app on the Android platform in one of the following ways:

  • 在實體裝置上︰ 使用 USB 纜線將 Android 裝置連接至開發電腦。On a physical device: Attach your Android device to your development computer with a USB cable. 請選取 [裝置],不要選取 [Google Android 模擬器]。Instead of Google Android Emulator, select Device. Visual Studio 會將應用程式部署至裝置,並執行應用程式。Visual Studio deploys the application to the device and runs the application. 您接著可以在裝置上與應用程式互動。You can then interact with the application on the device.

    Mobizen 等螢幕畫面分享應用程式可協助您開發 Android 應用程式。Screen-sharing applications such as Mobizen can assist you in developing Android applications. Mobizen 會將您的 Android 畫面投射至電腦上的網頁瀏覽器。Mobizen projects your Android screen to a web browser on your PC.

  • 在 Android 模擬器上︰ 使用模擬器時,還需要其他設定步驟。On an Android emulator: There are additional configuration steps that are required when you're using an emulator.

    請確定您是部署至已將 Google API 設為目標的虛擬裝置,如 Android 虛擬裝置 (AVD) 管理員中所示。Make sure you are deploying to a virtual device that has Google APIs set as the target, as shown in the Android Virtual Device (AVD) manager.

    Android 虛擬裝置管理員

    如果您想要使用更快速的 x86 模擬器,請安裝 HAXM 驅動程式,並設定模擬器來使用它。If you want to use a faster x86 emulator, install the HAXM driver, and then configure the emulator to use it.

    選取 [應用程式] > [設定] > [新增帳戶] 將 Google 帳戶加入 Android 裝置。Add a Google account to the Android device by selecting Apps > Settings > Add account. 然後遵循提示。Then follow the prompts.

    將 Google 帳戶新增至 Android 裝置

    按照先前的方法執行 todolist 應用程式,然後插入新的 todo 項目。Run the todolist app as before and insert a new todo item. 這次,通知圖示會顯示在通知區域中。This time, a notification icon is displayed in the notification area. 您可以開啟通知抽屜來檢視通知的完整內容。You can open the notification drawer to view the full text of the notification.

    檢視通知

(選擇性) 在 iOS 上設定和執行(Optional) Configure and run on iOS

本節適用於在 iOS 裝置上執行 Cordova 專案。This section is for running the Cordova project on iOS devices. 如果未使用 iOS 裝置,可以略過這一節。If you aren't working with iOS devices, you can skip this section.

在 Mac 或雲端服務上安裝及執行 iOS 遠端組建代理程式Install and run the iOS remote build agent on a Mac or cloud service

您必須先進行 iOS 安裝指南中的步驟來安裝和執行遠端組建代理程式,才可以使用 Visual Studio 在 iOS 上執行 Cordova 應用程式。Before you can run a Cordova app on iOS using Visual Studio, go through the steps in the iOS setup guide to install and run the remote build agent.

確定您可以建置適用於 iOS 的應用程式。Make sure you can build the app for iOS. 必須執行安裝指南中的步驟才能從 Visual Studio 針對 iOS 建置應用程式。The steps in the setup guide are required for building the app for iOS from Visual Studio. 如果您沒有 Mac,您可以在 MacInCloud 之類的服務上使用遠端組建代理程式來針對 iOS 建置。If you do not have a Mac, you can build for iOS by using the remote build agent on a service like MacInCloud. 如需詳細資訊,請參閱在雲端中執行 iOS 應用程式For more information, see Run your iOS app in the cloud.

注意

必須有 Xcode 7 或更新版本,才能在 iOS 上使用推播外掛程式。Xcode 7 or greater is required to use the push plugin on iOS.

尋找要做為應用程式識別碼的識別碼Find the ID to use as your App ID

在針對推播通知註冊您的應用程式之前,在 Cordova 應用程式中開啟 config.xml,在 widget 元素中尋找 id 屬性值,並加以複製以供稍後使用。Before you register your app for push notifications, open config.xml in your Cordova app, find the id attribute value in the widget element, and then copy it for later use. 在下列 XML 中,識別碼為 io.cordova.myapp7777777In the following XML, the ID is io.cordova.myapp7777777.

<widget defaultlocale="en-US" id="io.cordova.myapp7777777"
    version="1.0.0" windows-packageVersion="1.1.0.0" xmlns="http://www.w3.org/ns/widgets"
    xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:vs="http://schemas.microsoft.com/appx/2014/htmlapps">

稍後,當您在 Apple 開發人員入口網站上建立應用程式識別碼時,請使用這個識別碼。Later, use this identifier when you create an App ID on Apple's developer portal. 如果您在開發人員入口網站上建立不同的應用程式識別碼,在本教學課程稍後,您必須採取一些額外的步驟。If you create a different App ID on the developer portal, you must take a few extra steps later in this tutorial. Widget 元素中的識別碼必須符合開發人員入口網站上的應用程式識別碼。The ID in the widget element must match the App ID on the developer portal.

在 Apple 的開發人員入口網站註冊應用程式以取得推播通知Register the app for push notifications on Apple's developer portal

觀看示範類似步驟的影片Watch a video showing similar steps

設定 Azure 來傳送推播通知Configure Azure to send push notifications

  1. 在您的 Mac 上啟動 Keychain AccessOn your Mac, launch Keychain Access. 在左側導覽列的 [類別] 下,開啟 [我的憑證]。On the left navigation bar, under Category, open My Certificates. 尋找您在上一節中下載的 SSL 憑證,然後公開其內容。Find the SSL certificate that you downloaded in the previous section, and then disclose its contents. 僅選取憑證 (不選取私密金鑰)。Select only the certificate (do not select the private key). 然後將它匯出Then export it.
  2. Azure 入口網站中,選取 [瀏覽全部] > [應用程式服務]。In the Azure portal, select Browse All > App Services. 然後選取您的 Mobile Apps 後端。Then select your Mobile Apps back end.
  3. 在 [設定] 下,選取 [App Service 推播]。Under Settings, select App Service Push. 然後選取您的通知中樞名稱。Then select your notification hub name.
  4. 移至 [Apple 推播通知服務] > [上傳憑證]。Go to Apple Push Notification Services > Upload Certificate. 上傳 .p12 檔案,選取正確的模式 (根據您稍早的用戶端 SSL 憑證為生產或沙箱)。Upload the .p12 file, selecting the correct Mode (depending on whether your client SSL certificate from earlier is production or sandbox). 儲存任何變更。Save any changes.

您的服務現在已設定成在 iOS 上使用推播通知。Your service is now configured to work with push notifications on iOS.

確認您的應用程式識別碼符合 Cordova 應用程式Verify that your App ID matches your Cordova app

如果您在 Apple 開發人員帳戶中建立的應用程式識別碼已符合 config.xml 檔案中 widget 元素的識別碼,即可略過此步驟。If the App ID that you created in your Apple Developer Account already matches the ID of the widget element in the config.xml file, you can skip this step. 不過,如果識別碼不相符,請採取下列步驟︰However, if the IDs don't match, take the following steps:

  1. 從您的專案中刪除 platforms 資料夾。Delete the platforms folder from your project.
  2. 從您的專案中刪除 plugins 資料夾。Delete the plugins folder from your project.
  3. 從您的專案中刪除 node_modules 資料夾。Delete the node_modules folder from your project.
  4. 在 config.xml 檔案中更新 widget 元素的 id 屬性,以使用您在 Apple 開發人員帳戶中建立的應用程式識別碼。Update the id attribute of the widget element in the config.xml file to use the app ID that you created in your Apple developer account.
  5. 重建您的專案。Rebuild your project.
在 iOS 應用程式中測試推播通知Test push notifications in your iOS app
  1. 在 Visual Studio 中,請確定已選取 iOS 作為部署目標。In Visual Studio, make sure that iOS is selected as the deployment target. 然後選取 [裝置] 以在連接的 iOS 裝置上執行推播通知。Then select Device to run the push notifications on your connected iOS device.

    您可以在連接至 PC 與 iTunes 的 iOS 裝置上執行推播通知。You can run the push notifications on an iOS device that's connected to your PC with iTunes. iOS 模擬器不支援推播通知。The iOS Simulator does not support push notifications.

  2. 在 Visual Studio 中選取 [執行] 按鈕或 F5 以建置專案,並在 iOS 裝置上啟動應用程式。Select the Run button or F5 in Visual Studio to build the project and start the app in an iOS device. 然後,選取 [確定] 以接收推播通知。Then select OK to accept push notifications.

    注意

    應用程式在第一次執行期間會要求您確認推播通知。The app requests confirmation for push notifications during the first run.

  3. 在應用程式中輸入一項工作,然後選取加號 (+) 圖示。In the app, type a task, and then select the plus (+) icon.

  4. 驗證已收到通知。Verify that a notification was received. 然後選取 [確定] 關閉通知。Then select OK to dismiss the notification.

(選擇性) 在 Windows 上設定和執行(Optional) Configure and run on Windows

本節說明如何在 Windows 10 裝置 (Windows 10 支援 PhoneGap 推播外掛程式) 上執行 Apache Cordova 應用程式專案。This section describes how to run the Apache Cordova app project on Windows 10 devices (the PhoneGap push plugin is supported on Windows 10). 如果未使用 Windows 裝置,可以略過這一節。If you are not working with Windows devices, you can skip this section.

向 WNS 註冊 Windows 應用程式以使用推播通知Register your Windows app for push notifications with WNS

若要使用 Visual Studio 中的 [存放區] 選項,請從 [解決方案平台] 清單中選取 Windows 目標,例如 Windows-x64Windows-x86To use the Store options in Visual Studio, select a Windows target from the Solution Platforms list, such as Windows-x64 or Windows-x86. (避免 Windows-AnyCPU 使用推播通知。)(Avoid Windows-AnyCPU for push notifications.)

  1. 在 Visual Studio 方案總管中,以滑鼠右鍵按一下 Windows 市集應用程式專案。In Visual Studio Solution Explorer, right-click the Windows Store app project. 然後選取 [市集] > [將應用程式與市集建立關聯]。Then select Store > Associate App with the Store.

    建立應用程式與 Windows 市集的關聯

  2. 在精靈中,選取 [下一步]。In the wizard, select Next. 然後使用您的 Microsoft 帳戶登入。Then sign in with your Microsoft account. 在 [保留新的應用程式名稱] 中,輸入您應用程式的名稱,然後選取 [保留]。In Reserve a new app name, type a name for your app, and then select Reserve.
  3. 成功建立應用程式註冊之後,選取新的應用程式名稱。After the app registration is successfully created, select the new app name. 選取 [下一步],然後選取 [關聯]。Select Next, and then select Associate. 此程序會將所需的 Windows 市集註冊資訊新增至應用程式資訊清單。This process adds the required Windows Store registration information to the application manifest.
  4. 使用您之前為 Windows 市集應用程式所建立的相同註冊,針對 Windows Phone 市集應用程式專案重複步驟 1 和 3。Repeat steps 1 and 3 for the Windows Phone Store app project by using the same registration you previously created for the Windows Store app.
  5. 移至 Windows 開發人員中心,然後使用您的 Microsoft 帳戶登入。Go to the Windows Dev Center, and then sign in with your Microsoft account. 在 [我的應用程式] 中,選取新的應用程式註冊。In My apps, select the new app registration. 然後展開 [服務] > [推播通知]。Then expand Services > Push notifications.
  6. 在 [推播通知] 頁面上,在 [Windows 推播通知服務 (WNS) 和 Microsoft Azure Mobile Apps] 下,選取 [線上服務網站]。On the Push notifications page, under Windows Push Notification Services (WNS) and Microsoft Azure Mobile Apps, select Live Services site. 請記下套件 SID 的值和應用程式密碼中的目前值。Make a note of the values of the Package SID and the current value in Application Secret.

    開發人員中心的應用程式設定

    重要

    應用程式密碼與封裝 SID 是重要的安全性認證。The application secret and package SID are important security credentials. 請勿與任何人共用這些值,或與您的應用程式一起散發密碼。Don't share these values with anyone or distribute them with your app.

觀看示範類似步驟的影片Watch a video showing similar steps

設定 WNS 的通知中樞Configure the notification hub for WNS

  1. Azure 入口網站中,選取 [瀏覽全部] > [應用程式服務]。In the Azure portal, select Browse All > App Services. 然後選取您的 Mobile Apps 後端。Then select your Mobile Apps back end. 在 [設定] 下,選取 [App Service 推播]。Under Settings, select App Service Push. 然後選取您的通知中樞名稱。Then select your notification hub name.
  2. 移至 Windows (WNS)Go to Windows (WNS). 然後輸入您從線上服務網站取得的 [安全性金鑰] (用戶端秘密) 和 [封裝 SID]。Then enter the Security key (client secret) and Package SID that you obtained from the Live Services site. 接下來,選取 [儲存]。Next, select Save.

    在入口網站中設定 WNS 金鑰

您的後端現在已設定成使用 WNS 傳送來傳送推播通知。Your back end is now configured to use WNS to send push notifications.

設定 Cordova 應用程式以支援 Windows 推播通知Configure your Cordova app to support Windows push notifications

以滑鼠右鍵按一下 config.xml 開啟設定設計工具。Open the configuration designer by right-clicking config.xml. 然後選取 [檢視設計工具]。Then select View Designer. 接下來,選取 [Windows] 索引標籤,然後在 [Windows 目標版本] 底下選取 [Windows 10]。Next, select the Windows tab, and then select Windows 10 under Windows Target Version.

若要在您的預設 (偵錯) 組建中支援推播通知,請開啟 build.json 檔案。To support push notifications in your default (debug) builds, open the build.json file. 然後將 "release" 設定複製到您的偵錯設定。Then copy the "release" configuration to your debug configuration.

"windows": {
    "release": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
    }
}

更新之後,build.json 檔案應該包含下列程式碼︰After the update, the build.json file should contain the following code:

"windows": {
    "release": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
        },
    "debug": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
        }
    }

建置應用程式並確認沒有錯誤。Build the app and verify that you have no errors. 您的用戶端應用程式現在應註冊來自 Mobile Apps 後端的通知。Your client app should now register for the notifications from the Mobile Apps back end. 針對方案中每個 Windows 專案重複操作這一節。Repeat this section for every Windows project in your solution.

在 Windows 應用程式中測試推播通知Test push notifications in your Windows app

在 Visual Studio 中,確定已選取 Windows 平台做為部署目標,例如 Windows-x64Windows-x86In Visual Studio, make sure that a Windows platform is selected as the deployment target, such as Windows-x64 or Windows-x86. 若要在裝載 Visual Studio 的 Windows 10 電腦上執行應用程式,請選擇 [本機電腦]。To run the app on a Windows 10 PC that's hosting Visual Studio, choose Local Machine.

  1. 選取 [執行] 按鈕,以建置專案並啟動應用程式。Select the Run button to build the project and start the app.

  2. 在應用程式中輸入新 todoitem 的名稱,然後選取加號 (+) 圖示來加入它。In the app, type a name for a new todoitem, and then select the plus (+) icon to add it.

確認在加入項目時收到通知。Verify that a notification is received when the item is added.

後續步驟Next steps

  • 請參閱通知中樞,以了解推播通知的相關資訊。Read about Notification Hubs to learn about push notifications.
  • 繼續教學課程,在 Apache Cordova 應用程式中新增驗證 (如果尚未這麼做)。If you have not already done so, continue the tutorial by adding authentication to your Apache Cordova app.

了解如何使用下列 SDK:Learn how to use the following SDKs: