教程:使用 Azure 通知中心向 Xamarin.iOS 应用推送通知Tutorial: Push notifications to Xamarin.iOS apps using Azure Notification Hubs

概述Overview

本教程演示如何使用 Azure 通知中心将推送通知发送到 iOS 应用程序。This tutorial shows you how to use Azure Notification Hubs to send push notifications to an iOS application. 你将创建一个空白 Xamarin.iOS 应用,它使用 Apple Push Notification 服务 (APNs) 接收推送通知。You create a blank Xamarin.iOS app that receives push notifications by using the Apple Push Notification service (APNs).

完成后,你将能够使用通知中心将推送通知广播到运行你的应用的所有设备。When you're finished, you are able to use your notification hub to broadcast push notifications to all the devices running your app. NotificationHubs 应用示例中提供了完成的代码。The finished code is available in the NotificationHubs app sample.

在本教程中,你创建/更新代码来执行以下任务:In this tutorial, you create/update code to do the following tasks:

  • 生成证书签名请求文件Generate the certificate signing request file
  • 为推送通知注册应用程序Register your app for push notifications
  • 为应用程序创建配置文件Create a provisioning profile for the app
  • 针对 iOS 推送通知配置通知中心Configure your notification hub for iOS push notifications
  • 发送测试推送通知Send test push notifications

先决条件Prerequisites

  • Azure 订阅Azure subscription. 如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a Trial before you begin.

  • 最新版本的 XcodeLatest version of Xcode

  • iOS 10(或更高版本)兼容设备An iOS 10 (or later version) compatible device

  • Apple 开发人员计划 成员身份。Apple Developer Program membership.

  • Visual Studio for MacVisual Studio for Mac

    Note

    由于 iOS 推送通知配置要求,你必须在物理 iOS 设备(iPhone 或 iPad)而不是在模拟器上部署和测试示例应用程序。Because of configuration requirements for iOS push notifications, you must deploy and test the sample application on a physical iOS device (iPhone or iPad) instead of in the simulator.

只有在完成本教程后,才能完成有关 Xamarin iOS 应用的所有其他通知中心教程。Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for Xamarin.iOS apps.

生成证书签名请求文件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 请求新证书

  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 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 登录,依次选择“Identifiers”(标识符)、“App IDs”(应用 ID)、“+”,以便注册新应用。 After that, sign in with your Apple ID, select Identifiers, select App IDs, and finally select + to register a new app.

    iOS 预配门户应用 ID 页

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

    • 名称:在“App ID Description”(应用 ID 说明)部分的“Name”(名称)框中为应用键入一个描述性名称 。Name: Type a descriptive name for your app in the Name box in the App ID Description section.

    • Bundle Identifier(捆绑标识符):在“Explicit App ID”(显式应用 ID)部分,使用应用分发指南中所述的 <Organization Identifier>.<Product Name> 格式输入“Bundle Identifier”(捆绑标识符) 。Bundle Identifier: In the Explicit App ID section, enter a Bundle Identifier 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 will use the correct publishing profile.

    • Push Notifications(推送通知):在“App Services”(应用程序服务)部分选中“Push Notifications”(推送通知)选项 。Push Notifications: Check the Push Notifications option in the App Services section.

      用于注册新应用 ID 的窗体

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

      选择“Register”(注册)后,会看到“Registration complete”(注册已完成)屏幕,如下图所示。 After you select Register, you see the Registration complete screen as shown in the following image. 选择“完成” 。Select Done.

      应用 ID 注册完成,显示了权利

  3. 在开发人员中心的“App IDs”(应用 ID)下,找到创建的应用 ID,并选择它所在的行。 In the Developer Center, under App IDs, locate the app ID that you created and select its row.

    应用 ID 列表

    选择用于显示应用详细信息的应用 ID,然后选择底部的“Edit”(编辑)按钮。 Select the app ID to display the app details, and then select the Edit button at the bottom.

    编辑应用 ID 页

  4. 滚动到屏幕底部并选择“Development Push SSL Certificate”(开发推送 SSL 证书)部分下的“Create Certificate”(创建证书)按钮。 Scroll to the bottom of the screen and select the Create Certificate button under the Development Push SSL Certificate section.

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

    现在会显示“Add iOS Certificate”(添加 iOS 证书)助手。 You now see the Add iOS Certificate assistant.

    Note

    本教程使用开发证书。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.

  5. 选择“Choose File”(选择文件),浏览到在第一个任务中保存 CSR 文件的位置,然后选择“Generate”(生成)。 Select Choose File, browse to the location where you saved the CSR file from the first task, and then select Generate.

    已生成证书的 CSR 上传页

  6. 门户创建证书后,请选择“Download”(下载)按钮,然后选择“Done”(完成)。 After the portal creates the certificate, select the Download button and then select Done.

    已生成证书的下载页

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

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

    Note

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

  7. 选择下载的推送证书 aps_development.cerSelect the downloaded push certificate aps_development.cer.

    此操作将在密钥链中安装新证书,如下图所示:This action installs the new certificate in the Keychain, as shown in the following image:

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

    Note

    证书中的名称可能会不同,但会以 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.

  8. 在 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 格式导出

    记下导出的 .p12 证书的文件名和位置。Make a note of the file name and location of the exported .p12 certificate. 它们用于启用 APNs 身份验证。They are used to enable authentication with APNs.

    Note

    本教程创建名为 QuickStart.p12 的文件。This tutorial creates a file named QuickStart.p12. 文件名和位置可能不同。Your file name and location might be different.

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

  1. iOS 预配门户中,依次选择“Provisioning Profiles”(预配配置文件)、“All”(全部)、“+”,以便创建新的配置文件。 In the iOS Provisioning Portal, select Provisioning Profiles, select All, and then select + to create a new profile. 此时会显示“Add iOS Provisiong Profile”(添加 iOS 预配配置文件)向导。 You see the Add iOS Provisioning Profile wizard.

    预配配置文件列表

  2. 在“Development”(开发)下选择“iOS App Development”(iOS 应用开发)作为预配配置文件类型,然后选择“Continue”(继续)。 Select iOS App Development under Development as the provisioning profile type, and 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 your usual development certificate that you used for code signing, and select Continue. 此证书不是所创建的推送证书。This certificate isn't the push certificate you created.

    选择证书

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

    选择设备

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

    选择预配配置文件名称

  7. 创建新的预配配置文件后,请选择下载该文件并将其安装在 Xcode 开发计算机上。When the new provisioning profile is created, choose to download and install it on your Xcode development machine. 然后选择“完成” 。Then select Done.

    下载预配配置文件

创建通知中心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.

    Important

    请勿 在应用程序中使用 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

  1. 在“通知服务”下选择“Apple (APNS)”。 Under Notification Services, select Apple (APNS).

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

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

  4. 选择前面导出的 .p12 文件。Select the .p12 file that you exported earlier.

  5. 指定正确的密码。Specify the correct password.

  6. 选择“沙盒” 模式。Select Sandbox mode. 仅当希望将推送通知发送给从应用商店购买应用的用户时,才应使用“生产”模式。 Use the Production mode only if you want to send push notifications to users who purchased your app from the store.

    在 Azure 门户中配置 APNs 证书

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

将应用连接到通知中心Connect your app to the notification hub

创建新项目Create a new project

  1. 在 Visual Studio 中创建新的 iOS 项目并选择“单视图应用”模板,然后单击“下一步” In Visual Studio, create a new iOS project and select the Single View App template, and click Next

    Visual Studio - 选择应用程序类型

  2. 输入应用名称和组织标识符,然后单击“下一步”和“创建”。 Enter your App Name and Organization identifier, then click Next, then Create

  3. 在“解决方案”视图中双击“Info.plist”, 确保“标识”下 的捆绑标识符与创建预配配置文件时使用的相符。From the Solution view, double-click Info.plist and under Identity make sure your Bundle Identifier matches the one used when creating your provisioning profile. 在“签名”下,确保 选中开发人员帐户;在“团队”下,确保选中“自动管理签名”。这样就会自动选中签名证书和预配配置文件。 Under Signing ensure that your Developer account is selected under Team, "Automatically manage signing" is selected and your Signing Certificate and Provisioning Profile are automatically selected.

    Visual Studio- iOS 应用配置

  4. 在“解决方案”视图中双击 Entitlements.plist,确保选中“启用推送通知”。 From the Solution view, double-click the Entitlements.plist and ensure that Enable Push Notifications is checked.

    Visual Studio - iOS 授权配置

  5. 添加 Azure 消息传送包。Add the Azure Messaging package. 在“解决方案”视图中右键单击项目,然后选择“添加” > “添加 NuGet 包”。In the Solution view, right-click the project and select Add > Add NuGet Packages. 搜索 Xamarin.Azure.NotificationHubs.iOS,向项目添加该包。Search for Xamarin.Azure.NotificationHubs.iOS and add the package to your project.

  6. 向类添加新文件,将其命名为 Constants.cs,然后添加以下变量,将字符串文本占位符替换为此前记下的 hubnameDefaultListenSharedAccessSignatureAdd a new file to your class, name it Constants.cs and add the following variables and replace the string literal placeholders with the hubname and the DefaultListenSharedAccessSignature noted earlier.

    // Azure app-specific connection string and hub path
    public const string ListenConnectionString = "<Azure DefaultListenSharedAccess Connection String>";
    public const string NotificationHubName = "<Azure Notification Hub Name>";
    
  7. AppDelegate.cs 中添加以下 using 语句:In AppDelegate.cs, add the following using statement:

    using WindowsAzure.Messaging;
    using UserNotifications
    
  8. 声明 SBNotificationHub 的实例:Declare an instance of SBNotificationHub:

    private SBNotificationHub Hub { get; set; }
    
  9. AppDelegate.cs 中更新 FinishedLaunching(),使之与以下代码匹配:In AppDelegate.cs, update FinishedLaunching() to match the following code:

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
                                                                    (granted, error) =>
            {
                if (granted)
                    InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
            });
        } else if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
            var pushSettings = UIUserNotificationSettings.GetSettingsForTypes (
                    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                    new NSSet ());
    
            UIApplication.SharedApplication.RegisterUserNotificationSettings (pushSettings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications ();
        } else {
            UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
            UIApplication.SharedApplication.RegisterForRemoteNotificationTypes (notificationTypes);
        }
    
        return true;
    }
    
  10. AppDelegate.cs 中重写 RegisteredForRemoteNotifications() 方法:In AppDelegate.cs, override the RegisteredForRemoteNotifications() method:

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);
    
        Hub.UnregisterAllAsync (deviceToken, (error) => {
            if (error != null)
            {
                System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
                return;
            }
    
            NSSet tags = null; // create tags if you want
            Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
                if (errorCallback != null)
                    System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
            });
        });
    }
    
  11. AppDelegate.cs 中重写 ReceivedRemoteNotification() 方法:In AppDelegate.cs, override the ReceivedRemoteNotification() method:

    public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
    {
        ProcessNotification(userInfo, false);
    }
    
  12. AppDelegate.cs 中创建 ProcessNotification() 方法:In AppDelegate.cs, create the ProcessNotification() method:

    void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
    {
        // Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
        if (null != options && options.ContainsKey(new NSString("aps")))
        {
            //Get the aps dictionary
            NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;
    
            string alert = string.Empty;
    
            //Extract the alert text
            // NOTE: If you're using the simple alert by just specifying
            // "  aps:{alert:"alert msg here"}  ", this will work fine.
            // But if you're using a complex alert with Localization keys, etc.,
            // your "alert" object from the aps dictionary will be another NSDictionary.
            // Basically the JSON gets dumped right into a NSDictionary,
            // so keep that in mind.
            if (aps.ContainsKey(new NSString("alert")))
                alert = (aps [new NSString("alert")] as NSString).ToString();
    
            //If this came from the ReceivedRemoteNotification while the app was running,
            // we of course need to manually process things like the sound, badge, and alert.
            if (!fromFinishedLaunching)
            {
                //Manually show an alert
                if (!string.IsNullOrEmpty(alert))
                {
                    UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null);
                    avAlert.Show();
                }
            }
        }
    }
    

    Note

    可以选择重写 FailedToRegisterForRemoteNotifications() 以处理无网络连接等情况。You can choose to override FailedToRegisterForRemoteNotifications() to handle situations such as no network connection. 如果用户可能会在脱机模式(例如飞行模式)下启动应用程序,并且你想要处理应用特定的推送消息传送方案,则此操作特别重要。This is especially important where the user might start your application in offline mode (for example, Airplane) and you want to handle push messaging scenarios specific to your app.

  13. 在设备上运行应用程序。Run the app on your device.

发送测试推送通知Send test push notifications

可以在 Azure 门户中使用“测试性发送”选项,在应用中测试通知的发送。You can test receiving notifications in your app with the Test Send option in the Azure portal. 它会向设备发送测试性的推送通知。It sends a test push notification to your device.

Azure 门户 - 测试性发送

通常,推送通知是在后端服务(例如,Mobile Apps,或者使用兼容库的 ASP.NET)中发送的。Push notifications are normally sent in a back-end service like Mobile Apps or ASP.NET using a compatible library. 如果后端没有可用库,也可使用 REST API 直接发送通知消息。If a library is not available for your back-end, you can also use the REST API directly to send notification messages.

后续步骤Next steps

本教程介绍了如何将广播通知发送到所有注册到后端的 iOS 设备。In this tutorial, you sent broadcast notifications to all your iOS devices registered with the backend. 若要了解如何向特定的 iOS 设备推送通知,请转到以下教程:To learn how to push notifications to specific iOS devices, advance to the following tutorial: