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

在本教程中,你将使用 Azure 通知中心向 iOS 应用程序推送通知。In this tutorial, you use Azure Notification Hubs to push notifications to an iOS application. 你将创建一个空白 iOS 应用,它使用 Apple Push Notification 服务 (APNs) 接收推送通知。You create a blank iOS app that receives push notifications by using the Apple Push Notification service (APNs).

在本教程中,你将执行以下步骤:In this tutorial, you take the following steps:

  • 生成证书签名请求文件Generate the certificate signing request file
  • 请求你的应用推送通知Request your app for push notifications
  • 为应用程序创建配置文件Create a provisioning profile for the app
  • 针对 iOS 推送通知配置通知中心Configure your notification hub for iOS push notifications
  • 将 iOS 应用连接到通知中心Connect your iOS app to notification hubs
  • 发送测试推送通知Send test push notifications
  • 验证应用可以接收通知Verify that your app receives notifications

可以 在 GitHub 上找到本教程的已完成代码。The completed code for this tutorial can be found on GitHub.

先决条件Prerequisites

  • 有效的 Azure 帐户。An active Azure account. 如果没有帐户,可以创建一个试用帐户,只需几分钟即可完成。If you don't have an account, you can create a trial account in just a couple of minutes.

  • Windows Azure Messaging FrameworkWindows Azure Messaging Framework

  • 最新版本的 XcodeLatest version of Xcode

  • 支持 iOS 10(或更高版本)的设备An iOS 10 (or later version)-capable device

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

    Note

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

完成本教程是学习有关 iOS 应用的所有其他通知中心教程的先决条件。Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for 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 is used by Apple 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 launch pad.

  2. 单击“Keychain Access”,展开“Certificate Assistant”(证书助理),并单击“Request a Certificate from a Certificate Authority...”(从证书颁发机构请求证书...)。Click Keychain Access, expand Certificate Assistant, then click Request a Certificate from a Certificate Authority....

    使用 Keychain Access 请求新证书

  3. 选择“用户电子邮件地址”和“公用名称”,确保已选择“保存到磁盘”,并单击“继续”。Select your User Email Address and Common Name, make sure that Saved to disk is selected, and then click Continue. 将“CA Email Address”(CA 电子邮件地址)字段保留空白,因为它不是必填字段 。Leave the CA Email Address field blank as it is not required.

    所需证书信息

  4. 在“Save As”(另存为)中为证书签名请求 (CSR) 文件键入一个名称,在“Where”(位置)中选择一个位置,并单击“Save”(保存)。Type a name for the Certificate Signing Request (CSR) file in Save As, select the location in Where, then click Save.

    为证书选择一个文件名

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

接下来,将要向 Apple 注册应用、启用推送通知并上传导出的 CSR 以创建一个推送证书。Next, you 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 be able to send push notifications to an iOS app, you must register your application with Apple and also register for push notifications.

  1. 如果尚未注册应用程序,请导航到 Apple 开发人员中心的 iOS 设置门户,使用 Apple ID 登录,单击“Identifiers”(标识符),然后单击“App IDs”(应用 ID),最后单击“+”号注册新的应用。If you have not already registered your app, navigate to the iOS Provisioning Portal at the Apple Developer Center, sign in with your Apple ID, click Identifiers, then click App IDs, and finally click on the + sign to register a new app.

    iOS 预配门户应用 ID 页

  2. 更新新应用的以下三个字段,并单击“Continue”(继续): Update the following three fields for your new app and then click Continue:

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

    • Bundle Identifier(捆绑标识符):在“Explicit App ID”(显式应用 ID)部分下,使用应用分发指南中所述的 <Organization Identifier>.<Product Name> 格式输入“Bundle Identifier”(捆绑标识符)。Bundle Identifier: Under the Explicit App ID section, enter a Bundle Identifier in the form <Organization Identifier>.<Product Name> as mentioned in the App Distribution Guide. 使用的“Organization Identifier”(组织标识符)和“Product Name”(产品名称)必须与在创建 XCode 项目时使用的组织标识符与产品名称匹配。The Organization Identifier and Product Name you use must match the organization identifier and product name you use when you create your XCode project. 在下面的屏幕截图中,NotificationHubs 用作组织标识符,GetStarted 用作产品名称。In the following screenshot NotificationHubs is used as an organization identifier and GetStarted is used as the product name. 如果确保此值与在 XCode 项目中使用的值匹配,则就可以在 XCode 中使用正确的发布配置文件。Making sure this value matches the value you use in your XCode project allows you to use the correct publishing profile with XCode.

    • 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 you to confirm the information. 单击“Register”(注册)确认新的应用 ID。Click Register to confirm the new App ID.

      单击“注册”后,会看到“注册已完成”屏幕,如下图所示。Once you click Register, you see the Registration complete screen, as shown in the following image. 单击“Done”(完成) 。Click Done.

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

  3. 在开发人员中心的“App IDs”(应用 ID)下,找到创建的应用 ID,然后单击其所在行。In the Developer Center, under App IDs, locate the app ID that you created, and click on its row.

    应用 ID 列表

    单击应用 ID 会显示应用详细信息。Clicking on the app ID displays the app details. 单击底部的“Edit”(编辑)按钮。Click the Edit button at the bottom.

    编辑应用 ID 页

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

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

    将显示“添加 iOS 证书”助手。You 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”(生成)。Click Choose File, browse to the location where you saved the CSR file that you created in the first task, then click Generate.

    已生成证书的 CSR 上传页

  6. 门户创建证书之后,单击“Download”(下载)按钮,然后单击“Done”(完成)。After the certificate is created by the portal, click the Download button, and click Done.

    已生成证书的下载页

    这将下载证书并将其保存到计算机上的 Downloads 文件夹。It downloads the certificate and saves it to your computer in your Downloads folder.

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

    Note

    默认情况下,下载的文件(开发证书)名为 aps_development.cer。By default, the downloaded file a development certificate is named aps_development.cer.

  7. 双击下载的推送证书 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 证书列表,显示了新证书

    Note

    证书中的名称可能会不同,但将以 Apple Development iOS Push Services 作为前缀。The name in your certificate might be different, but it 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. 单击“导出”,为文件命名,选择“.p12”格式,并单击“保存”。Click Export, name the file, select the .p12 format, and then click Save.

    将证书作为 p12 格式导出

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

    Note

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

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

  1. 返回 iOS 预配门户,选择“Provisioning Profiles”(预配配置文件),选择“All”(全部),并单击 +(加号)按钮创建一个新的配置文件。Back in the iOS Provisioning Portal, select Provisioning Profiles, select All, and then click the + (plus) button to create a new profile. 将显示“添加 iOS 预配配置文件”向导:You see the Add iOS Provisioning Profile wizard:

    预配配置文件列表

  2. 选择“开发”下的“iOS 应用程序开发”作为预配配置文件类型,并单击“继续”。Select iOS App Development under Development as the provisioning profile type, and click Continue.

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

    选择应用 ID

  4. 在“Select certificates”(选择证书)屏幕中,选择经常用于代码签名的开发证书,然后单击“Continue”(继续)。In the Select certificates screen, select your usual development certificate used for code signing, and click Continue. 此证书不是所创建的推送证书。This certificate is not the push certificate you created.

    选择证书

  5. 接下来,选择要用于测试的“Devices”(设备),并单击“Continue”(继续)。Next, select the Devices to use for testing, and click Continue

    选择设备

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

    选择预配配置文件名称

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

    下载预配配置文件

将 iOS 应用连接到通知中心Connect your iOS app to Notification Hubs

  1. 在 Xcode 中,创建新的 iOS 项目,然后选择“单视图应用程序”模板 。In Xcode, create a new iOS project and select the Single View Application template.

    Xcode — 单一视图应用程序

  2. 设置新项目的选项时,请务必使用在 Apple 开发人员门户中设置捆绑标识符时使用的同一产品名称组织标识符When setting the options for your new project, make sure to use the same Product Name and Organization Identifier that you used when you set the bundle identifier in the Apple Developer portal.

    Xcode — 项目选项

  3. 在“项目导航器”下单击项目名称,然后单击“常规”选项卡,找到“签名”。 Under Project Navigator, click your project name, click the General tab, and find Signing. 确保为 Apple 开发人员帐户选择适当的团队。Make sure you select the appropriate Team for your Apple Developer account. XCode 会根据捆绑标识符自动下拉以前创建的预配配置文件。XCode should automatically pull down the Provisioning Profile you created previously based on your bundle identifier.

    如果屏幕未显示在 Xcode 中创建的新预配配置文件,请尝试刷新签名标识的配置文件。If you don't see the new provisioning profile that you created in Xcode, try refreshing the profiles for your signing identity. 单击菜单栏上的“Xcode”,再依次单击“首选项”、“帐户”选项卡、“查看详细信息”按钮、你的签名标识,然后单击右下角的刷新按钮 。Click Xcode on the menu bar, click Preferences, click the Account tab, click the View Details button, click your signing identity, and then click the refresh button in the bottom-right corner.

    Xcode — 预配配置文件

  4. 选择“功能”选项卡,确保启用“推送通知” Select the Capabilities tab and make sure to enable Push Notifications

    Xcode - 推送功能

  5. 添加 Azure 通知中心 SDK 模块。Add the Azure Notification Hubs SDK modules.

    可以在应用中集成 Azure 通知中心 SDK,方法是使用 Cocoapods 或者手动将二进制文件添加到项目。You can integrate the Azure Notification Hubs SDK in your app by using Cocoapods or by manually adding the binaries to your project.

    • 通过 Cocoapods 进行集成Integration via Cocoapods

      将以下依赖项添加到 podfile,以便将 Azure 通知中心 SDK 包括到应用中。Add the following dependencies to your podfile to include Azure Notification Hubs SDK into your app.

      pod 'AzureNotificationHubs-iOS'
      

      运行 pod install,以便安装新定义的 Pod 并打开 .xcworkspaceRun pod install to install your newly defined pod and open your .xcworkspace.

      Note

      如果在运行 pod install 时看到 [!] Unable to find a specification for `AzureNotificationHubs-iOS` 之类的错误,请运行 pod repo update 以从 Cocoapods 存储库获取最新 Pod,然后运行 pod installIf you see an error like [!] Unable to find a specification for `AzureNotificationHubs-iOS` while running pod install, please run pod repo update to get the latest pods from the Cocoapods repository and then run pod install.

    • 通过 Carthage 进行集成Integration via Carthage

      将以下依赖项添加到 Cartfile,以便将 Azure 通知中心 SDK 包括到应用中。Add the following dependencies to your Cartfile to include Azure Notification Hubs SDK into your app.

      github "Azure/azure-notificationhubs-ios"
      

      接下来,更新并生成依赖项:Next, update, and build dependencies:

      $ carthage update
      

      有关如何使用 Carthage 的详细信息,请参阅 Carthage GitHub 存储库For more information about using Carthage, see the Carthage GitHub repository.

    • 通过将二进制文件复制到项目中进行集成Integration by copying the binaries into your project

      1. 下载以 zip 文件形式提供的 Azure 通知中心 SDK 框架,然后将其解压缩。Download the Azure Notification Hubs SDK framework provided as a zip file and unzip it.

      2. 在 Xcode 中,右键单击项目,然后单击“将文件添加到”选项,将 WindowsAzureMessaging.framework 文件夹添加到 Xcode 项目 。In Xcode, right-click your project and click the Add Files to option to add the WindowsAzureMessaging.framework folder to your Xcode project. 选择“选项”,确保选中“根据需要复制项目”,然后单击“添加”。 Select Options and make sure Copy items if needed is selected, and then click Add.

        解压缩 Azure SDK

  6. 将新的标头文件添加到名为 HubInfo.h 的项目。Add a new header file to your project named HubInfo.h. 此文件保存着通知中心的常量。This file holds the constants for your notification hub. 添加以下定义,然后将字符串文本占位符替换为中心名称以及前面记下的 DefaultListenSharedAccessSignatureAdd the following definitions and replace the string literal placeholders with your hub name and the DefaultListenSharedAccessSignature noted earlier.

    #ifndef HubInfo_h
    #define HubInfo_h
    
        #define HUBNAME @"<Enter the name of your hub>"
        #define HUBLISTENACCESS @"<Enter your DefaultListenSharedAccess connection string"
    
    #endif /* HubInfo_h */
    
  7. 打开 AppDelegate.h 文件并添加以下导入指令:Open your AppDelegate.h file add the following import directives:

    #import <WindowsAzureMessaging/WindowsAzureMessaging.h>
    #import <UserNotifications/UserNotifications.h>
    #import "HubInfo.h"
    
  8. 根据 iOS 版本,在 AppDelegate.m 文件的 didFinishLaunchingWithOptions 方法中添加以下代码。In your AppDelegate.m file, add the following code in the didFinishLaunchingWithOptions method based on your version of iOS. 此代码向 APNs 注册设备句柄:This code registers your device handle with APNs:

    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound |
        UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  9. 在同一文件中添加以下方法:In the same file, add the following methods:

        - (void) application:(UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *) deviceToken {
        SBNotificationHub* hub = [[SBNotificationHub alloc] initWithConnectionString:HUBLISTENACCESS
                                    notificationHubPath:HUBNAME];
    
        [hub registerNativeWithDeviceToken:deviceToken tags:nil completion:^(NSError* error) {
            if (error != nil) {
                NSLog(@"Error registering for notifications: %@", error);
            }
            else {
                [self MessageBox:@"Registration Status" message:@"Registered"];
            }
        }];
        }
    
    -(void)MessageBox:(NSString *) title message:(NSString *)messageText
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:messageText preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:okAction];
        [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alert animated:YES completion:nil];
    }
    

    此代码将使用在 HubInfo.h 中指定的连接信息连接到通知中心。This code connects to the notification hub using the connection information you specified in HubInfo.h. 然后,它向通知中心提供设备令牌,使通知中心能够发送通知。It then gives the device token to the notification hub so that the notification hub can send notifications.

  10. 在同一文件中,添加以下方法以便在应用处于活动状态时收到通知的情况下显示 UIAlertIn the same file, add the following method to display a UIAlert if the notification is received while the app is active:

    - (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo {
        NSLog(@"%@", userInfo);
        [self MessageBox:@"Notification" message:[[userInfo objectForKey:@"aps"] valueForKey:@"alert"]];
    }
    
  11. 若要验证是否没有故障,请在设备上生成并运行应用。To verify there are no failures, build and 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.

下面是你可能想要查看的有关发送通知的其他教程列表:Here is a list of some other tutorials you may want to review for sending notifications:

验证应用可以接收推送通知Verify that your app receives push notifications

要在 iOS 上测试推送通知,必须将应用部署到物理 iOS 设备。To test push notifications on iOS, you must deploy the app to a physical iOS device. 不能使用 iOS 模拟器发送 Apple 推送通知。You cannot send Apple push notifications by using the iOS Simulator.

  1. 运行应用并验证注册是否成功,然后按“确定” 。Run the app and verify that registration succeeds, and then press OK.

    iOS 应用推送通知注册测试

  2. 如上一部分所述,接下来可以从 Azure 门户发送测试推送通知。Next you send a test push notification from the Azure portal, as described in the previous section.

  3. 该推送通知会从特定通知中心发送到所有已注册为接收通知的设备。The push notification is sent to all devices that are registered to receive the notifications from the particular Notification Hub.

    iOS 应用推送通知接收测试

后续步骤Next steps

在这个简单的示例中,已将推送通知广播到所有已注册的 iOS 设备。In this simple example, you broadcasted push notifications to all your registered iOS devices. 若要了解如何向特定的 iOS 设备推送通知,请转到以下教程:To learn how to push notifications to specific iOS devices, advance to the following tutorial: