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

Note

Visual Studio App Center 正在投资于对移动应用开发至关重要的新集成服务。Visual Studio App Center is investing in new and integrated services central to mobile app development. 开发人员可以使用生成测试分发服务来设置持续集成和交付管道。Developers can use Build, Test and Distribute services to set up Continuous Integration and Delivery pipeline. 部署应用后,开发人员可以使用分析诊断服务监视其应用的状态和使用情况,并使用推送服务与用户互动。Once the app is deployed, developers can monitor the status and usage of their app using the Analytics and Diagnostics services, and engage with users using the Push service. 开发人员还可以利用 Auth 对用户进行身份验证,利用数据服务在云中持久保存和同步应用数据。Developers can also leverage Auth to authenticate their users and Data service to persist and sync app data in the cloud. 立即查看 App CenterCheck out App Center today.

概述Overview

本教程介绍如何向 Xamarin.iOS 快速入门项目添加推送通知,以便每次插入一条记录时,向设备发送一条推送通知。In this tutorial, you add push notifications to the Xamarin.iOS quick start project so that a push notification is sent to the device 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 后端服务器 SDKSee Work with the .NET backend server SDK for Azure Mobile Apps for more information.

先决条件Prerequisites

在 Apple 的开发人员门户上为推送通知注册应用Register the app for push notifications on Apple's developer portal

配置移动应用以发送推送通知Configure your Mobile App to send push notifications

  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.

更新服务器项目以发送推送通知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.

配置 Xamarin.iOS 项目Configure your Xamarin.iOS project

在 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.

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

  1. QSTodoService 中,添加以下属性使 AppDelegate 可以获取移动客户端:In QSTodoService, add the following property so that AppDelegate can acquire the mobile client:

    public MobileServiceClient GetClient {
        get
        {
            return client;
        }
        private set
        {
            client = value;
        }
    }
    
  2. AppDelegate.cs 文件顶部添加以下 using 语句。Add the following using statement to the top of the AppDelegate.cs file.

    using Microsoft.WindowsAzure.MobileServices;
    using Newtonsoft.Json.Linq;
    
  3. AppDelegate 中,重写 FinishedLaunching 事件:In AppDelegate, override the FinishedLaunching event:

     public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
     {
         // registers for push for iOS8
         var settings = UIUserNotificationSettings.GetSettingsForTypes(
             UIUserNotificationType.Alert
             | UIUserNotificationType.Badge
             | UIUserNotificationType.Sound,
             new NSSet());
    
         UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
         UIApplication.SharedApplication.RegisterForRemoteNotifications();
    
         return true;
     }
    
  4. 在同一文件中,重写 RegisteredForRemoteNotifications 事件。In the same file, override the RegisteredForRemoteNotifications event. 在此代码中,将注册一个简单的模板通知,服务器会将此通知发送到所有支持的平台。In this code you are registering for a simple template notification that will be sent across all supported platforms by the server.

    有关使用通知中心的模板的详细信息,请参阅模板For more information on templates with Notification Hubs, see Templates.

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        MobileServiceClient client = QSTodoService.DefaultService.GetClient;
    
        const string templateBodyAPNS = "{\"aps\":{\"alert\":\"$(messageParam)\"}}";
    
        JObject templates = new JObject();
        templates["genericMessage"] = new JObject
        {
            {"body", templateBodyAPNS}
        };
    
        // Register for push with your mobile app
        var push = client.GetPush();
        push.RegisterAsync(deviceToken, templates);
    }
    
  5. 然后,重写 DidReceivedRemoteNotification 事件:Then, override the DidReceivedRemoteNotification event:

     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();
         }
     }
    

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

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

  1. 在支持 iOS 的设备中按“运行” 按钮,以生成项目并启动应用,然后单击“确定” 接受推送通知。Press the Run button to build the project and start the app in an iOS capable device, then click OK to accept push notifications.

    Note

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

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

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

  4. 重复步骤 2 并立即关闭应用,并检查是否已显示通知。Repeat step 2 and immediately close the app, then verify that a notification is shown.

已成功完成本教程。You have successfully completed this tutorial.