将推送通知添加到 iOS 应用Add Push Notifications to your 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

本教程介绍如何向 iOS 快速入门项目添加推送通知,以便每次插入一条记录时,都向设备发送一条推送通知。In this tutorial, you add push notifications to the iOS quickstart project so that a push notification is sent to the device every time a record is inserted.

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

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

配置通知中心Configure 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.

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

配置 Azure 以发送推送通知Configure Azure 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 backend to send push notifications

.NET 后端 (C#).NET backend (C#):

  1. 在 Visual Studio 中,右键单击服务器项目并单击“管理 NuGet 包” ,搜索 Microsoft.Azure.NotificationHubs,然后单击“安装” 。In Visual Studio, right-click the server project and click Manage NuGet Packages, search for Microsoft.Azure.NotificationHubs, then click Install. 这会安装通知中心库,以便从后端发送通知。This installs the Notification Hubs library for sending notifications from your backend.

  2. 在后端的 Visual Studio 项目中,依次打开“控制器” > “TodoItemController.cs” 。In the backend's Visual Studio project, open Controllers > TodoItemController.cs. 在文件的顶部,添加以下 using 语句:At the top of the file, add the following using statement:

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. PostTodoItem 方法替换为以下代码:Replace the PostTodoItem method with the following code:

    public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
    {
        TodoItem current = await InsertAsync(item);
        // 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);
    
        // iOS payload
        var appleNotificationPayload = "{\"aps\":{\"alert\":\"" + item.Text + "\"}}";
    
        try
        {
            // Send the push notification and log the results.
            var result = await hub.SendAppleNativeNotificationAsync(appleNotificationPayload);
    
            // 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");
        }
        return CreatedAtRoute("Tables", new { id = current.Id }, current);
    }
    
  4. 重新发布服务器项目。Republish the server project.

Node.js 后端Node.js backend:

  1. 设置后端项目。Set up your backend project.

  2. 用以下代码替换 todoitem.js 表脚本:Replace the todoitem.js table script 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();
    
    // When adding record, send a push notification via APNS
    table.insert(function (context) {
        // For details of the Notification Hubs JavaScript SDK, 
        // see https://aka.ms/nodejshubs
        logger.info('Running TodoItem.insert');
    
        // Create a payload that contains the new item Text.
        var payload = "{\"aps\":{\"alert\":\"" + context.item.text + "\"}}";
    
        // Execute the insert; Push as a post-execute action when results are returned as a Promise.
        return context.execute()
            .then(function (results) {
                // Only do the push if configured
                if (context.push) {
                    context.push.apns.send(null, payload, function (error) {
                        if (error) {
                            logger.error('Error while sending push notification: ', error);
                        } else {
                            logger.info('Push notification sent successfully!');
                        }
                    });
                }
                return results;
            })
            .catch(function (error) {
                logger.error('Error while running context.execute: ', error);
            });
    });
    
    module.exports = table;
    
  3. 编辑本地计算机上的文件时,请重新发布服务器项目。When editing the file on your local computer, republish the server project.

将推送通知添加到应用Add push notifications to app

Objective-CObjective-C:

  1. 在 QSAppDelegate.m 中,导入 iOS SDK 和 QSTodoService.h :In QSAppDelegate.m, import the iOS SDK and QSTodoService.h:

    #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h>
    #import "QSTodoService.h"
    
  2. 在 QSAppDelegate.m 中的 didFinishLaunchingWithOptions 内,紧靠 return YES; 前方插入以下行 :In didFinishLaunchingWithOptions in QSAppDelegate.m, insert the following lines right before return YES;:

    UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  3. 在“QSAppDelegate.m” 中,添加以下处理程序方法。In QSAppDelegate.m, add the following handler methods. 应用现已更新,可支持推送通知。Your app is now updated to support push notifications.

    // Registration with APNs is successful
    - (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
        QSTodoService *todoService = [QSTodoService defaultService];
        MSClient *client = todoService.client;
    
        [client.push registerDeviceToken:deviceToken completion:^(NSError *error) {
            if (error != nil) {
                NSLog(@"Error registering for notifications: %@", error);
            }
        }];
    }
    
    // Handle any failure to register
    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:
    (NSError *)error {
        NSLog(@"Failed to register for remote notifications: %@", error);
    }
    
    // Use userInfo in the payload to display an alert.
    - (void)application:(UIApplication *)application
            didReceiveRemoteNotification:(NSDictionary *)userInfo {
        NSLog(@"%@", userInfo);
    
        NSDictionary *apsPayload = userInfo[@"aps"];
        NSString *alertString = apsPayload[@"alert"];
    
        // Create alert with notification content.
        UIAlertController *alertController = [UIAlertController
                                        alertControllerWithTitle:@"Notification"
                                        message:alertString
                                        preferredStyle:UIAlertControllerStyleAlert];
    
        UIAlertAction *cancelAction = [UIAlertAction
                                        actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel")
                                        style:UIAlertActionStyleCancel
                                        handler:^(UIAlertAction *action)
                                        {
                                            NSLog(@"Cancel");
                                        }];
    
        UIAlertAction *okAction = [UIAlertAction
                                    actionWithTitle:NSLocalizedString(@"OK", @"OK")
                                    style:UIAlertActionStyleDefault
                                    handler:^(UIAlertAction *action)
                                    {
                                        NSLog(@"OK");
                                    }];
    
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
    
        // Get current view controller.
        UIViewController *currentViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
        while (currentViewController.presentedViewController)
        {
            currentViewController = currentViewController.presentedViewController;
        }
    
        // Display alert.
        [currentViewController presentViewController:alertController animated:YES completion:nil];
    
    }
    

SwiftSwift:

  1. 将文件“ClientManager.swift” 与以下内容一起添加。Add file ClientManager.swift with the following contents. 用 Azure 移动应用后端的 URL 替换“%AppUrl%” 。Replace %AppUrl% with the URL of the Azure Mobile App backend.

    class ClientManager {
        static let sharedClient = MSClient(applicationURLString: "%AppUrl%")
    }
    
  2. 在 ToDoTableViewController.swift 中,用以下行替换用于初始化 MSClientlet client 行 :In ToDoTableViewController.swift, replace the let client line that initializes an MSClient with this line:

    let client = ClientManager.sharedClient
    
  3. 在 AppDelegate.swift 中,如下所示替换 func application 的正文 :In AppDelegate.swift, replace the body of func application as follows:

    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound],
                categories: nil))
        application.registerForRemoteNotifications()
        return true
    }
    
  4. 在“AppDelegate.swift” 中,添加以下处理程序方法。In AppDelegate.swift, add the following handler methods. 应用现已更新,可支持推送通知。Your app is now updated to support push notifications.

    func application(application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        ClientManager.sharedClient.push?.registerDeviceToken(deviceToken) { error in
            print("Error registering for notifications: ", error?.description)
        }
    }
    
    func application(application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print("Failed to register for remote notifications: ", error.description)
    }
    
    func application(application: UIApplication,
        didReceiveRemoteNotification userInfo: [NSObject: AnyObject]) {
    
        print(userInfo)
    
        let apsNotification = userInfo["aps"] as? NSDictionary
        let apsString       = apsNotification?["alert"] as? String
    
        let alert = UIAlertController(title: "Alert", message: apsString, preferredStyle: .Alert)
        let okAction = UIAlertAction(title: "OK", style: .Default) { _ in
            print("OK")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { _ in
            print("Cancel")
        }
    
        alert.addAction(okAction)
        alert.addAction(cancelAction)
    
        var currentViewController = self.window?.rootViewController
        while currentViewController?.presentedViewController != nil {
            currentViewController = currentViewController?.presentedViewController
        }
    
        currentViewController?.presentViewController(alert, animated: true) {}
    
    }
    

测试推送通知Test push notifications

  • 在 Xcode 中,按“运行”并在 iOS 设备上(而非模拟器中)启动应用。单击“确定”接受推送通知;此请求只会在首次运行应用时出现。In Xcode, press Run and start the app on an iOS device (not the simulator.) Click OK to accept push notifications; this request occurs the first time the app runs.

  • 在应用中,添加新项并单击“+”。In the app, add a new item and click +.

  • 检查是否已收到通知,并单击“确定”以取消通知 。Verify that a notification is received, then click OK to dismiss the notification. 现已成功完成本教程。You have now successfully completed this tutorial.

    ![](../articles/media/mobile-services-ios-get-started-push/mobile-quickstart-push3-ios.png)
    

其他信息More