向 Xamarin.Forms 应用添加推送通知Add push notifications to your Xamarin.Forms app

概述Overview

在本教程中,可以将推送通知添加到从 Xamarin.Forms 快速启动生成的所有项目。In this tutorial, you add push notifications to all the projects that resulted from the Xamarin.Forms quick start. 这意味着,每次插入一条记录,都会向所有跨平台客户端发送一条推送通知。This means that a push notification is sent to all cross-platform clients every time a record is inserted.

如果不使用下载的快速入门服务器项目,则需要推送通知扩展包。If you do not use the downloaded quick start server project, you will need the push notification extension package. 有关详细信息,请参阅使用用于 Azure 移动应用的 .NET 后端服务器 SDKFor more information, see Work with the .NET backend server SDK for Azure Mobile Apps.

必备条件Prerequisites

对于 iOS,用户需要 Apple 开发人员计划成员身份和物理 iOS 设备。For iOS, you will need an Apple Developer Program membership and a physical iOS device. iOS 模拟器不支持推送通知The iOS simulator does not support push notifications.

配置通知中心Configure a notification hub

Azure 应用服务的移动应用功能使用 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.

    配置中心

现在已将通知中心连接到移动应用后端项目。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.

更新服务器项目以发送推送通知Update the server project to send push notifications

在本部分中,更新现有移动应用后端项目中的代码,以便在每次添加新项目时推送通知。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. 在服务器项目中,打开“控制器” > “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. 设置后端项目。Set up your backend project.

  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 https://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.

配置和运行 iOS 项目(可选)Configure and run the iOS project (optional)

本部分用于运行适用于 iOS 设备的 Xamarin iOS 项目。This section is for running the Xamarin iOS project for iOS devices. 如果不使用 iOS 设备,可以跳过本部分。You can skip this section if you are not working with iOS devices.

生成证书签名请求文件Generate the certificate-signing request file

Apple Push Notification 服务 (APNs) 使用证书对推送通知进行身份验证。The Apple Push Notification Service (APNs) uses certificates to authenticate your push notifications. 请遵照这些说明来创建用于发送和接收通知的所需推送证书。Follow these instructions to create the necessary push certificate to send and receive notifications. 有关这些概念的详细信息,请参阅正式的 Apple Push Notification 服务文档。For more information on these concepts, see the official Apple Push Notification Service documentation.

生成证书签名请求 (CSR) 文件,Apple 将使用该文件生成签名的推送证书。Generate the Certificate Signing Request (CSR) file, which Apple uses to generate a signed push certificate.

  1. 在 Mac 上,运行 Keychain Access 工具。On your Mac, run the Keychain Access tool. 可以从启动台上的“Utilities”或“Other”文件夹中打开该工具。 It can be opened from the Utilities folder or the Other folder on the Launchpad.

  2. 选择“Keychain Access”,展开“Certificate Assistant”(证书助理),然后选择“Request a Certificate from a Certificate Authority”(从证书颁发机构请求证书)。 Select Keychain Access, expand Certificate Assistant, and then select Request a Certificate from a Certificate Authority.

    使用 Keychain Access 请求新证书

    备注

    默认情况下,Keychain Access 选择列表中的第一项。By default, Keychain Access selects the first item in the list. 如果你位于“Certificates”(证书) 类别中,并且“Apple Worldwide Developer Relations Certification Authority”(Apple 全球开发者关系证书颁发机构) 不是列表中的第一项,这可能会是个问题。This can be a problem if you're in the Certificates category and Apple Worldwide Developer Relations Certification Authority is not the first item in the list. 在生成 CSR(证书签名请求)之前,请确保已有非密钥项,或者已选择“Apple Worldwide Developer Relations Certification Authority”(Apple 全球开发者关系证书颁发机构) 密钥。Make sure you have a non-key item, or the Apple Worldwide Developer Relations Certification Authority key is selected, before generating the CSR (Certificate Signing Request).

  3. 选择“User Email Address”(用户电子邮件地址),输入“Common Name”(公用名)值,确保指定“Saved to disk”(保存到磁盘),然后选择“Continue”(继续)。 Select your User Email Address, enter your Common Name value, make sure that you specify Saved to disk, and then select Continue. 将“CA Email Address”(CA 电子邮件地址)留空,因为它不是必填字段 。Leave CA Email Address blank as it isn't required.

    所需证书信息

  4. 在“Save As”(另存为)中为 CSR 文件输入一个名称,在“Where”(位置)中选择位置,然后选择“Save”(保存)。 Enter a name for the CSR file in Save As, select the location in Where, and then select Save.

    为证书选择一个文件名

    此操作会将 CSR 文件保存到选定位置。This action saves the CSR file in the selected location. 默认位置为“桌面”。 The default location is Desktop. 请记住为此文件选择的位置。Remember the location chosen for the file.

接下来,向 Apple 注册应用,启用推送通知并上传导出的 CSR,以便创建推送证书。Next, register your app with Apple, enable push notifications, and upload the exported CSR to create a push certificate.

为推送通知注册应用程序Register your app for push notifications

若要将推送通知发送到 iOS 应用,请向 Apple 注册应用程序,还要注册推送通知。To send push notifications to an iOS app, register your application with Apple, and also register for push notifications.

  1. 如果尚未注册应用,请浏览到 Apple 开发人员中心的 iOS 预配门户If you haven't already registered your app, browse to the iOS Provisioning Portal at the Apple Developer Center. 使用你的 Apple ID 登录到门户,然后选择“标识符” 。Sign in to the portal with your Apple ID, and select Identifiers. 然后选择 + 注册新应用。Then select + to register a new app.

    iOS 预配门户应用 ID 页

  2. 在“注册新的标识符” 屏幕上,选择“应用 ID” 单选按钮。On the Register a New Identifier screen, select the App IDs radio button. 然后选择“继续”。 Then select Continue.

    iOS 预配门户“注册新 ID”页

  3. 更新新应用的以下三个值,然后选择“Continue”(继续): Update the following three values for your new app, and then select Continue:

    • 说明:键入应用的描述性名称。Description: Type a descriptive name for your app.

    • 捆绑 ID:按应用分发指南中所述,输入格式为 Organization Identifier.Product Name 的捆绑 ID。Bundle ID: Enter a Bundle ID of the form Organization Identifier.Product Name as mentioned in the App Distribution Guide. “Organization Identifier”(组织标识符)和“Product Name”(产品名称)值必须与创建 Xcode 项目时使用的组织标识符与产品名称匹配。 The Organization Identifier and Product Name values must match the organization identifier and product name you use when you create your Xcode project. 在下面的屏幕截图中,NotificationHubs 值用作组织标识符,GetStarted 值用作产品名称。In the following screenshot, the NotificationHubs value is used as an organization identifier and the GetStarted value is used as the product name. 确保“Bundle Identifier”(捆绑标识符)值与 Xcode 项目中的值匹配,这样 Xcode 就可以使用正确的发布配置文件。 Make sure the Bundle Identifier value matches the value in your Xcode project, so that Xcode uses the correct publishing profile.

      iOS 预配门户“注册应用 ID”页

    • Push Notifications(推送通知):在“Capabilities”(功能)部分选中“Push Notifications”(推送通知)选项 。Push Notifications: Check the Push Notifications option in the Capabilities section.

      用于注册新应用 ID 的窗体

      此操作会生成应用 ID 并请求你确认信息。This action generates your App ID and requests that you confirm the information. 选择“Continue”(继续),然后选择“Register”(注册) 以确认新的应用 ID。Select Continue, then select Register to confirm the new App ID.

      确认新的应用 ID

      选择“Register”(注册) 后,新的应用 ID 将作为行项出现在“Certificates, Identifiers & Profiles”(证书、标识符和配置文件) 页中。After you select Register, you see the new App ID as a line item in the Certificates, Identifiers & Profiles page.

  4. 在“Certificates, Identifiers & Profiles”(证书、标识符和配置文件) 页的“Identifiers”(标识符) 下,找到你刚刚创建的应用 ID 行项,并选择其所在的行以显示“Edit your App ID Configuration”(编辑应用 ID 配置) 屏幕。In the Certificates, Identifiers & Profiles page, under Identifiers, locate the App ID line item that you just created, and select its row to display the Edit your App ID Configuration screen.

为通知中心创建证书Creating a Certificate for Notification Hubs

必须有证书才能使通知中心与 APNS 配合工作。A certificate is required to enable the notification hub to work with APNS. 可通过以下两种方式之一实现此目的:This can be done in one of two ways:

  1. 创建可以直接上传到通知中心的 .p12 。Create a .p12 that can be uploaded directly to Notification Hub.
  2. 创建可用于基于令牌的身份验证的 .p8 (较新的方法 )。Create a .p8 that can be used for token-based authentication (the newer approach).

基于令牌 (HTTP/2) 的 APNS 身份验证中所述,较新的方法(与使用证书相比)有很多好处。The newer approach has a number of benefits (compared to using certificates) as documented in Token-based (HTTP/2) authentication for APNS. 不过,下面为这两种方法都提供了步骤。However, steps have been provided for both approaches.

选项 1:创建可以直接上传到通知中心的 .p12 推送证书OPTION 1: Creating a .p12 push certificate that can be uploaded directly to Notification Hub

  1. 向下滚动到选中的“Push Notifications”(推送通知) 选项,然后选择“Configure”(配置) 以创建证书。Scroll down to the checked Push Notifications option, and then select Configure to create the certificate.

    编辑应用 ID 页

  2. 此时将显示“Apple Push Notification service SSL Certificates”(Apple 推送通知服务 SSL 证书) 窗口。The Apple Push Notification service SSL Certificates window appears. 选择“Development SSL Certificate”(开发 SSL 证书) 部分下的“Create Certificate”(创建证书) 按钮。Select the Create Certificate button under the Development SSL Certificate section.

    “为应用 ID 创建证书”按钮

    此时将显示“Create a new Certificate”(创建新证书) 屏幕。The Create a new Certificate screen is displayed.

    备注

    本教程使用开发证书。This tutorial uses a development certificate. 注册生产证书时使用相同的过程。The same process is used when registering a production certificate. 只需确保在发送通知时使用相同的证书类型。Just make sure that you use the same certificate type when sending notifications.

  3. 选择“Choose File”(选择文件),浏览到在第一个任务中保存 CSR 文件的位置,然后双击证书名以加载该证书。 Select Choose File, browse to the location where you saved the CSR file from the first task, and then double-click the certificate name to load it. 然后选择“继续”。 Then select Continue.

  4. 当门户创建证书后,请选择“Download”(下载)按钮。 After the portal creates the certificate, select the Download button. 保存证书,并记住保存证书的位置。Save the certificate, and remember the location to which it's saved.

    已生成证书的下载页

    这将下载证书并将其保存到计算机的 Downloads 文件夹。The certificate is downloaded and saved to your computer in your Downloads folder.

    在 Downloads 文件夹中找到证书文件

    备注

    默认情况下,下载的开发证书名为 aps_development.cerBy default, the downloaded development certificate is named aps_development.cer.

  5. 双击下载的推送证书 aps_development.cerDouble-click the downloaded push certificate aps_development.cer. 此操作将在密钥链中安装新证书,如下图所示:This action installs the new certificate in the Keychain, as shown in the following image:

    Keychain Access 证书列表,显示了新证书

    备注

    证书中的名称可能会不同,但会以 Apple Development iOS Push Services 作为前缀。Although the name in your certificate might be different, the name will be prefixed with Apple Development iOS Push Services.

  6. 在 Keychain Access 中,右键单击在“Certificates”(证书)类别中创建的新推送证书 。In Keychain Access, right-click the new push certificate that you created in the Certificates category. 选择“Export”(导出),为文件命名,选择“.p12”格式,并选择“Save”(保存)。 Select Export, name the file, select the .p12 format, and then select Save.

    将证书作为 p12 格式导出

    可以选择使用密码保护证书,但这是可选的。You can choose to protect the certificate with a password, but this is optional. 如果要跳过密码创建,请单击“OK”(确定) 。Click OK if you want to bypass password creation. 记下导出的 .p12 证书的文件名和位置。Make a note of the file name and location of the exported .p12 certificate. 它们用于启用 APNs 身份验证。They are used to enable authentication with APNs.

    备注

    你的 .p12 文件名和位置可能不同于本教程中所示的名称和位置。Your .p12 file name and location might be different than what is pictured in this tutorial.

选项 2:创建可用于基于令牌的身份验证的 .p8 证书OPTION 2: Creating a .p8 certificate that can be used for token-based authentication

  1. 请记下以下详细信息:Make note of the following details:

    • 应用 ID 前缀 (这是团队 ID )App ID Prefix (this is a Team ID)
    • 捆绑包 ID Bundle ID
  2. 返回到“证书、标识符和配置文件” ,单击“密钥” 。Back in Certificates, Identifiers & Profiles, click Keys.

    备注

    如果已为 APNS 配置了密钥,则可以重复使用在创建后立即下载的 .p8 证书。If you already have a key configured for APNS, you can re-use the .p8 certificate that you downloaded right after it was created. 如果是这样,则可以忽略步骤 3 到步骤 5 。If so, you can ignore steps 3 through 5.

  3. 单击 + 按钮(或“创建密钥” 按钮)以创建新密钥。Click the + button (or the Create a key button) to create a new key.

  4. 提供合适的“密钥名称” 值,选中“Apple 推送通知服务(APNs)” 选项,然后单击“继续” ,接下来在下一个屏幕上单击“注册” 。Provide a suitable Key Name value, then check the Apple Push Notifications service (APNs) option, and then click Continue, followed by Register on the next screen.

  5. 单击“下载” ,然后将 .p8 文件(前缀为 AuthKey_ )移动到安全的本地目录,然后单击“完成” 。Click Download and then move the .p8 file (prefixed with AuthKey_) to a secure local directory, then click Done.

    备注

    请确保将 .p8 文件保存在安全的地方(并保存备份)。Be sure to keep your .p8 file in a secure place (and save a backup). 密钥在下载后无法重新下载,因为服务器副本已删除。After downloading your key, it cannot be re-downloaded as the server copy is removed.

  6. 在“密钥” 上,单击刚创建的密钥(如果已选择使用现有密钥,则改为单击现有密钥)。On Keys, click on the key that you just created (or an existing key if you have chosen to use that instead).

  7. 记下“密钥 ID”值。 Make note of the Key ID value.

  8. 在所选的合适应用程序(如 Visual Studio Code)中打开 .p8 证书,然后记下密钥值。Open your .p8 certificate in a suitable application of your choice such as Visual Studio Code then make note of the key value. 这是“-----BEGIN PRIVATE KEY-----” 和“-----END PRIVATE KEY-----” 之间的值。This is the value between -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- .

    -----BEGIN PRIVATE KEY-----
    <key_value>
    -----END PRIVATE KEY-----
    

    备注

    这是稍后将用于配置通知中心的令牌值 。This is the token value that will be used later to configure Notification Hub.

完成这些步骤后,你应具有稍后要在使用 APNs 信息配置通知中心中使用的以下信息:At the end of these steps you should have the following information for use later in Configure your notification hub with APNs information:

  • 团队 ID (请参阅步骤 1)Team ID (see step 1)
  • 捆绑包 ID (请参阅步骤 1)Bundle ID (see step 1)
  • 密钥 ID (请参阅步骤 7)Key ID (see step 7)
  • 令牌值 ,即 .p8 密钥值(请参阅步骤 8)Token value i.e. the .p8 key value (see step 8)

为应用程序创建配置文件Create a provisioning profile for the app

  1. 返回到 iOS 预配门户,选择“Certificates, Identifiers & Profiles”(证书、标识符和配置文件) ,从左侧菜单中选择“Profiles”(配置文件) ,然后选择 + 创建新的配置文件。Return to the iOS Provisioning Portal, select Certificates, Identifiers & Profiles, select Profiles from the left menu, and then select + to create a new profile. 此时将显示“Register a New Provisioning Profile”(注册新的预配配置文件) 屏幕。The Register a New Provisioning Profile screen appears.

  2. 选择“Development”(开发)下的“iOS App Development”(iOS 应用程序开发)作为预配配置文件类型,然后选择“Continue”(继续)。 Select iOS App Development under Development as the provisioning profile type, and then select Continue.

    预配配置文件列表

  3. 接下来,从“App ID”(应用 ID)下拉列表中选择创建的应用 ID,然后选择“Continue”(继续)。 Next, select the app ID you created from the App ID drop-down list, and select Continue.

    选择应用 ID

  4. 在“Select certificates”(选择证书)窗口中,选择用于代码签名的开发证书,然后选择“Continue”(继续)。 In the Select certificates window, select the development certificate that you use for code signing, and select Continue. 此证书不是所创建的推送证书。This certificate isn't the push certificate you created. 如果不存在,则必须创建一个。If one does not exist, you must create it. 如果证书存在,请跳到下一步。If a certificate does exist, skip to the next step. 若要创建开发证书(如果开发证书不存在),请执行以下操作:To create a development certificate if one does not exist:

    1. 如果看到“No Certificates are available”(没有可用的证书) ,请选择“Create Certificate”(创建证书) 。If you see No Certificates are available, select Create Certificate.
    2. 在“Software”(软件) 部分中,选择“Apple Development”(Apple 开发) 。In the Software section, select Apple Development. 然后选择“继续”。 Then select Continue.
    3. 在“Create a new Certificate”(创建新证书) 屏幕中,选择“Choose File”(选择文件) 。In the Create a New Certificate screen, select Choose File.
    4. 浏览到之前创建的“Certificate Signing Request”(证书签名请求) 证书,选择该证书,然后选择“Open”(打开) 。Browse to the Certificate Signing Request certificate you created earlier, select it, and then select Open.
    5. 选择“继续”。 Select Continue.
    6. 下载开发证书,并记住其保存位置。Download the development certificate, and remember the location to which it's saved.
  5. 返回到“Certificates, Identifiers & Profiles”(证书、标识符和配置文件) 页,从左侧菜单中选择“Profiles”(配置文件) ,然后选择 + 创建新的配置文件。Return to the Certificates, Identifiers & Profiles page, select Profiles from the left menu, and then select + to create a new profile. 此时将显示“Register a New Provisioning Profile”(注册新的预配配置文件) 屏幕。The Register a New Provisioning Profile screen appears.

  6. 在“Select certificates”(选择证书)窗口中,选择你刚刚创建的开发证书。 In the Select certificates window, select the development certificate that you just created. 然后选择“继续”。 Then select Continue.

  7. 接下来,选择用于测试的设备,然后选择“Continue”(继续)。 Next, select the devices to use for testing, and select Continue.

  8. 最后,在“Provisioning Profile Name”(预配配置文件名称)中为概要文件选择一个名称,然后选择“Generate”(生成)。 Finally, choose a name for the profile in Provisioning Profile Name, and select Generate.

    选择预配配置文件名称

  9. 创建了新的预配配置文件后,选择“Download”(下载) 。When the new provisioning profile is created, select Download. 记住保存证书的位置。Remember the location to which it's saved.

  10. 浏览到预配配置文件所在的位置,然后双击该配置文件以将其安装在 Xcode 开发计算机上。Browse to the location of the provisioning profile, and then double-click it to install it on your Xcode development machine.

创建通知中心Create a notification hub

在本部分,我们创建一个通知中心,并使用以前创建的 .p12 推送证书配置 APNs 身份验证。In this section, you create a notification hub and configure authentication with APNs by using the .p12 push certificate that you previously created. 如果想要使用已创建的通知中心,可以跳到步骤 5。If you want to use a notification hub that you've already created, you can skip to step 5.

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 在左侧菜单上选择“所有服务” ,然后在“移动”部分中选择“通知中心”。 Select All services on the left menu, and then select Notification Hubs in the Mobile section. 选择服务名称旁边的星形图标,以便将服务添加到左侧菜单上的“收藏夹”部分。 Select the star icon next to the service name to add the service to the FAVORITES section on the left menu. 在将“通知中心” 添加到“收藏夹” 之后,在左侧菜单上选择它。After you add Notification Hubs to FAVORITES, select it on the left menu.

    Azure 门户 - 选择“通知中心”

  3. 在“通知中心” 页面上,在工具栏上选择“添加” 。On the Notification Hubs page, select Add on the toolbar.

    通知中心 -“添加”工具栏按钮

  4. 在“通知中心” 页面上,执行以下步骤:On the Notification Hub page, do the following steps:

    1. 将一个名称输入“通知中心”。 Enter a name in Notification Hub.

    2. 在“创建新的命名空间”中输入名称。 Enter a name in Create a new namespace. 命名空间包含一个或多个中心。A namespace contains one or more hubs.

    3. 从“位置”下拉列表框中选择值。 Select a value from the Location drop-down list box. 此值指定要在其中创建通知中心的位置。This value specifies the location in which you want to create the hub.

    4. 在“资源组”中选择现有的资源组,或者为新资源组创建一个名称。 Select an existing resource group in Resource Group, or create a name for a new resource group.

    5. 选择“创建” 。Select Create.

      Azure 门户 - 设置通知中心属性

  5. 选择“通知”(钟形图标),然后选择“转到资源” 。Select Notifications (the bell icon), and then select Go to resource. 还可以刷新“通知中心” 页上的列表,然后选择通知中心。You can also refresh the list on the Notification Hubs page and select your hub.

    Azure 门户 - 通知 -> 转到资源

  6. 从列表中选择“访问策略” 。Select Access Policies from the list. 记下向你提供的两个连接字符串。Note that the two connection strings are available to you. 稍后在处理推送通知时需要它们。You'll need them later to handle push notifications.

    重要

    请勿 在应用程序中使用 DefaultFullSharedAccessSignature 策略。Do not use the DefaultFullSharedAccessSignature policy in your application. 这只能在后端使用。This is meant to be used in your back end only.

    Azure 门户 - 通知中心连接字符串

使用 APNs 信息配置通知中心Configure your notification hub with APNs information

在“Notification Services” 下,选择“Apple (APNS)” ,然后根据以前在为通知中心创建证书部分中选择的方法,执行相应的步骤。Under Notification Services, select Apple (APNS) then follow the appropriate steps based on the approach you chose previously in the Creating a Certificate for Notification Hubs section.

备注

仅当希望将推送通知发送给已从应用商店购买应用的用户时,才应当对“应用程序模式”使用“生产”。 Use the Production for Application Mode only if you want to send push notifications to users who purchased your app from the store.

选项 1:使用 .p12 推送证书OPTION 1: Using a .p12 push certificate

  1. 选择“证书”。 Select Certificate.

  2. 选择文件图标。Select the file icon.

  3. 选择前面导出的 .p12 文件,然后选择“Open”(打开) 。Select the .p12 file that you exported earlier, and then select Open.

  4. 如果需要,请指定正确的密码。If required, specify the correct password.

  5. 选择“沙盒” 模式。Select Sandbox mode.

    在 Azure 门户中配置 APNs 证书

  6. 选择“保存” 。Select Save.

选项 2:使用基于令牌的身份验证OPTION 2: Using token-based authentication

  1. 选择“令牌” 。Select Token.

  2. 输入前面获取的以下值:Enter the following values that you acquired earlier:

    • 密钥 ID Key ID
    • 捆绑包 ID Bundle ID
    • 团队 ID Team ID
    • 令牌 Token
  3. 选择“沙盒” Choose Sandbox

  4. 选择“保存” 。Select Save.

现在已使用 APNs 配置通知中心。You've now configured your notification hub with APNs. 此外还有了用于注册应用和发送推送通知的连接字符串。You also have the connection strings to register your app and send push notifications.

为 APNS 配置通知中心Configure the notification hub for APNS

  1. 在 Mac 上启动“Keychain Access”。 On 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. 然后选择“移动应用”后端。Then select your Mobile Apps back end.
  3. 在“设置”下 ,选择“应用服务推送” 。Under Settings, select App Service Push. 然后选择通知中心名称。Then select your notification hub name.
  4. 转到“Apple Push Notification 服务” > “上传证书”。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.

接下来,会在 Xamarin Studio 或 Visual Studio 中配置 iOS 项目设置。Next, you will configure the iOS project setting in Xamarin Studio or Visual Studio.

在 Xamarin Studio 中配置 iOS 项目Configure the iOS project in Xamarin Studio

  1. 在 Xamarin.Studio 中,打开 Info.plist,并使用前面随新应用 ID 创建的捆绑 ID 来更新“捆绑标识符” 。In Xamarin.Studio, open Info.plist, and update the Bundle Identifier with the bundle ID that you created earlier with your new app ID.

  2. 向下滚动到“后台模式” 。Scroll down to Background Modes. 选择“启用后台模式” 框和“远程通知” 框。Select the Enable Background Modes box and the Remote notifications box.

  3. 在解决方案面板中双击项目,打开“项目选项” 。Double-click your project in the Solution Panel to open Project Options.

  4. 在“生成” 下面选择“iOS 捆绑签名” ,选择刚为此项目设置的标识和预配配置文件。Under Build, choose iOS Bundle Signing, and select the corresponding identity and provisioning profile you just set up for this project.

    这确保项目使用新配置文件进行代码签名。This ensures that the project uses the new profile for code signing. 有关正式的 Xamarin 设备预配文档,请参阅 Xamarin 设备预配For the official Xamarin device provisioning documentation, see Xamarin Device Provisioning.

在 Visual Studio 配置 iOS 项目Configure the iOS project in Visual Studio

  1. 在 Visual Studio 中,右键单击项目,并单击“属性”。 In Visual Studio, right-click the project, and then click Properties.

  2. 在属性页中,单击“iOS 应用程序”选项卡,并使用先前创建的 ID 更新“标识符”。 In the properties pages, click the iOS Application tab, and update the Identifier with the ID that you created earlier.

  3. 在“iOS 捆绑签名” 选项卡中,选择刚为此项目设置的标识符和预配配置文件。In the iOS Bundle Signing tab, select the corresponding identity and provisioning profile you just set up for this project.

    这确保项目使用新配置文件进行代码签名。This ensures that the project uses the new profile for code signing. 有关正式的 Xamarin 设备预配文档,请参阅 Xamarin 设备预配For the official Xamarin device provisioning documentation, see Xamarin Device Provisioning.

  4. 双击 Info.plist 打开它,并在“后台模式”下启用“远程通知”。Double-click Info.plist to open it, and then enable RemoteNotifications under Background Modes.

向 iOS 应用添加推送通知Add push notifications to your iOS app

  1. iOS 项目中,打开 AppDelegate.cs,并在代码文件的顶部添加以下语句。In the iOS project, open AppDelegate.cs and add the following statement to the top of the code file.

    using Newtonsoft.Json.Linq;
    
  2. AppDelegate 类中,为 RegisteredForRemoteNotifications 事件添加重写以注册通知:In the AppDelegate class, add an override for the RegisteredForRemoteNotifications event to register for notifications:

    public override void RegisteredForRemoteNotifications(UIApplication application,
        NSData deviceToken)
    {
        const string templateBodyAPNS = "{\"aps\":{\"alert\":\"$(messageParam)\"}}";
    
        JObject templates = new JObject();
        templates["genericMessage"] = new JObject
            {
                {"body", templateBodyAPNS}
            };
    
        // Register for push with your mobile app
        Push push = TodoItemManager.DefaultManager.CurrentClient.GetPush();
        push.RegisterAsync(deviceToken, templates);
    }
    
  3. 并在 AppDelegate 中,为 DidReceiveRemoteNotification 事件处理程序添加以下重写:In AppDelegate, also add the following override for the DidReceiveRemoteNotification event handler:

    public override void DidReceiveRemoteNotification(UIApplication application,
        NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
    {
        NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
    
        string alert = string.Empty;
        if (aps.ContainsKey(new NSString("alert")))
            alert = (aps[new NSString("alert")] as NSString).ToString();
    
        //show alert
        if (!string.IsNullOrEmpty(alert))
        {
            UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null);
            avAlert.Show();
        }
    }
    

    运行该应用时,此方法可处理传入通知。This method handles incoming notifications while the app is running.

  4. AppDelegate 类中,向 FinishedLaunching 方法添加以下代码:In the AppDelegate class, add the following code to the FinishedLaunching method:

    // Register for push notifications.
    var settings = UIUserNotificationSettings.GetSettingsForTypes(
        UIUserNotificationType.Alert
        | UIUserNotificationType.Badge
        | UIUserNotificationType.Sound,
        new NSSet());
    
    UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
    UIApplication.SharedApplication.RegisterForRemoteNotifications();
    

    这会启用对远程通知的支持并请求推送注册。This enables support for remote notifications and requests push registration.

应用现已更新,可支持推送通知。Your app is now updated to support push notifications.

在 iOS 应用中测试推送通知Test push notifications in your iOS app

  1. 右键单击 iOS 项目,并单击“设为启动项目” 。Right-click the iOS project, and click Set as StartUp Project.

  2. 在 Visual Studio 中按“运行” 按钮或 F5 生成项目并在 iOS 设备中启动应用,Press the Run button or F5 in Visual Studio to build the project and start the app in an iOS device. 然后单击“确定”接受推送通知。 Then click OK to accept push notifications.

    备注

    必须显式接受来自应用程序的推送通知。You must explicitly accept push notifications from your app. 此请求只会在首次运行应用程序时出现。This request only occurs the first time that the app runs.

  3. 在应用中,键入一项任务,并单击加号 ( + ) 图标。In the app, type a task, and then click the plus (+) icon.

  4. 检查是否已收到通知,并单击“确定”以取消通知。 Verify that a notification is received, and then click OK to dismiss the notification.

配置和运行 Windows 项目(可选)Configure and run Windows projects (optional)

本部分用于运行适用于 Windows 设备的 Xamarin.Forms WinApp 和 WinPhone81 项目。This section is for running the Xamarin.Forms WinApp and WinPhone81 projects for Windows devices. 这些步骤也支持通用 Windows 平台 (UWP) 项目。These steps also support Universal Windows Platform (UWP) projects. 如果不使用 Windows 设备,可以跳过本部分。You can skip this section if you are not working with Windows devices.

将用于推送通知的 Windows 应用注册到 Windows 通知服务 (WNS)Register your Windows app for push notifications with Windows Notification Service (WNS)

  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 移动应用”下,选择“Live 服务站点”。 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.

为 WNS 配置通知中心Configure the notification hub for WNS

  1. Azure 门户中,选择“浏览全部” > “应用程序服务” 。In the Azure portal, select Browse All > App Services. 然后选择“移动应用”后端。Then select your Mobile Apps back end. 在“设置”下 ,选择“应用服务推送” 。Under Settings, select App Service Push. 然后选择通知中心名称。Then select your notification hub name.

  2. 转到“Windows (WNS)” 。Go to Windows (WNS). 输入安全密钥(客户端密码)和从 Live 服务站点获取的包 SIDThen 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.

向 Windows 应用添加推送通知Add push notifications to your Windows app

  1. 在 Visual Studio 中,打开 Windows 项目中的 App.xaml.cs,并添加以下语句。In Visual Studio, open App.xaml.cs in a Windows project, and add the following statements.

    using Newtonsoft.Json.Linq;
    using Microsoft.WindowsAzure.MobileServices;
    using System.Threading.Tasks;
    using Windows.Networking.PushNotifications;
    using <your_TodoItemManager_portable_class_namespace>;
    

    <your_TodoItemManager_portable_class_namespace> 替换为包含 TodoItemManager 类的可移植项目的命名空间。Replace <your_TodoItemManager_portable_class_namespace> with the namespace of your portable project that contains the TodoItemManager class.

  2. 在 App.xaml.cs 中,添加以下 InitNotificationsAsync 方法:In App.xaml.cs, add the following InitNotificationsAsync method:

    private async Task InitNotificationsAsync()
    {
        var channel = await PushNotificationChannelManager
            .CreatePushNotificationChannelForApplicationAsync();
    
        const string templateBodyWNS =
            "<toast><visual><binding template=\"ToastText01\"><text id=\"1\">$(messageParam)</text></binding></visual></toast>";
    
        JObject headers = new JObject();
        headers["X-WNS-Type"] = "wns/toast";
    
        JObject templates = new JObject();
        templates["genericMessage"] = new JObject
        {
            {"body", templateBodyWNS},
            {"headers", headers} // Needed for WNS.
        };
    
        await TodoItemManager.DefaultManager.CurrentClient.GetPush()
            .RegisterAsync(channel.Uri, templates);
    }
    

    此方法获取推送通知通道,并注册模板以从通知中心接收模板通知。This method gets the push notification channel, and registers a template to receive template notifications from your notification hub. 支持 messageParam 的模板通知将传送到此客户端。A template notification that supports messageParam will be delivered to this client.

  3. 在 App.xaml.cs 中,通过添加 async 修饰符更新 OnLaunched 事件处理程序方法定义。In App.xaml.cs, update the OnLaunched event handler method definition by adding the async modifier. 然后,在方法的末尾添加以下代码行:Then add the following line of code at the end of the method:

    await InitNotificationsAsync();
    

    这可确保每次启动应用时,创建或刷新推送通知注册。This ensures that the push notification registration is created or refreshed every time the app is launched. 请务必执行此操作,以保证 WNS 推送通道始终处于活动状态。It's important to do this to guarantee that the WNS push channel is always active.

  4. 在 Visual Studio 的解决方案资源管理器中,打开 Package.appxmanifest 文件,并在“通知”下将“支持 Toast 通知”设置为“是”。In Solution Explorer for Visual Studio, open the Package.appxmanifest file, and set Toast Capable to Yes under Notifications.

  5. 生成该应用并确认没有错误。Build the app and verify you have no errors. 客户端应用现在应从移动应用后端注册模板通知。Your client app should now register for the template 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

  1. 在 Visual Studio 中,右键单击 Windows 项目,并单击“设为启动项目” 。In Visual Studio, right-click a Windows project, and click Set as startup project.
  2. 按“运行”按钮生成项目并启动应用程序 。Press the Run button to build the project and start the app.
  3. 在应用中,为新 todoitem 键入一个名称,并单击加号 ( + ) 图标以添加它。In the app, type a name for a new todoitem, and then click the plus (+) icon to add it.
  4. 确认在添加该项目时收到了通知。Verify that a notification is received when the item is added.

后续步骤Next steps

可以了解有关推送通知的详细信息:You can learn more about push notifications:

也可继续学习以下教程之一:You can also continue on to one of the following tutorials:

  • 向应用添加身份验证Add authentication to your app
    了解如何使用标识提供者对应用的用户进行身份验证。Learn how to authenticate users of your app with an identity provider.
  • 为应用启用脱机同步Enable offline sync for your app
    了解如何使用移动应用后端向应用添加脱机支持。Learn how to add offline support for your app by using a Mobile Apps back end. 使用脱机同步,用户可以与移动应用进行交互—查看、添加或修改数据—,即使在没有网络连接时也是如此。With offline sync, users can interact with a mobile app—viewing, adding, or modifying data—even when there is no network connection.