将推送通知添加到 iOS 应用Add Push Notifications to your iOS App
概述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.
在 Azure 门户中,转到“应用服务” ,并选择应用后端。In the Azure portal, go to App Services, and then select your app back end. 在“设置” 下,选择“推送” 。Under Settings, select Push.
若要将通知中心资源添加到应用中,请选择“连接” 。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
为应用注册应用 ID。Register an App ID for your app. 创建显式应用 ID(不是通配符应用 ID),对于“绑定 ID”,使用与 Xcode 快速入门项目中完全相同的“绑定 ID”。Create an explicit App ID (not a wildcard App ID) and for Bundle ID, use the exact Bundle ID that is in your Xcode quickstart project. 此外,必须选中“推送通知”选项。It is also crucial that you check the Push Notifications option.
接下来,启用应用的推送通知。Next, enable push notifications for the app. 用户可以创建“开发”或“分发”SSL 证书(请记住稍后在 Azure 门户中选择相应的选项)。You may create either a "Development" or "Distribution" SSL certificate (remember to select the corresponding option in the Azure portal later.)
然后,验证应用 ID 是否启用了推送通知。Then, verify that the app ID enables push notifications.
最后,刷新 Xcode 快速入门项目中的预配配置文件并验证是否已创建或重新生成预配配置文件来启用推送通知。Finally, refresh the provisioning profiles in the Xcode quickstart project and verify that the provisioning profile was either created or regenerated to enable push notifications.
配置 Azure 以发送推送通知Configure Azure to send push notifications
- 在 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.
- 在 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.
- 转到“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#):
在 Visual Studio 中,右键单击服务器项目并单击“管理 NuGet 包” ,搜索
Microsoft.Azure.NotificationHubs
,并单击“安装” 。In Visual Studio, right-click the server project and click Manage NuGet Packages, search forMicrosoft.Azure.NotificationHubs
, then click Install. 这会安装通知中心库,以便从后端发送通知。This installs the Notification Hubs library for sending notifications from your backend.在后端的 Visual Studio 项目中,依次打开“控制器” > “TodoItemController.cs”。In the backend's Visual Studio project, open Controllers > TodoItemController.cs. 在文件的顶部,添加以下
using
语句:At the top of the file, add the followingusing
statement:using Microsoft.Azure.Mobile.Server.Config; using Microsoft.Azure.NotificationHubs;
将
PostTodoItem
方法替换为以下代码:Replace thePostTodoItem
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); }
重新发布服务器项目。Republish the server project.
Node.js 后端:Node.js backend:
设置后端项目。Set up your backend project.
用以下代码替换 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;
编辑本地计算机上的文件时,请重新发布服务器项目。When editing the file on your local computer, republish the server project.
向应用添加推送通知Add push notifications to app
Objective-C:Objective-C:
在 QSAppDelegate.m 中,导入 iOS SDK 和 QSTodoService.h:In QSAppDelegate.m, import the iOS SDK and QSTodoService.h:
#import <MicrosoftAzureMobile/MicrosoftAzureMobile.h> #import "QSTodoService.h"
在 QSAppDelegate.m 中的
didFinishLaunchingWithOptions
内,紧靠在return YES;
的前面插入以下行:IndidFinishLaunchingWithOptions
in QSAppDelegate.m, insert the following lines right beforereturn YES;
:UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings]; [[UIApplication sharedApplication] registerForRemoteNotifications];
在 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]; }
Swift:Swift:
将文件“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%") }
在 ToDoTableViewController.swift 中,用以下行替换用于初始化
MSClient
的let client
行:In ToDoTableViewController.swift, replace thelet client
line that initializes anMSClient
with this line:let client = ClientManager.sharedClient
在 AppDelegate.swift 中,如下所示替换
func application
的正文:In AppDelegate.swift, replace the body offunc 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 }
在 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.

更多More
- 使用模板可以灵活地发送跨平台推送和本地化推送。Templates give you flexibility to send cross-platform pushes and localized pushes. 如何使用适用于 Azure 移动应用的 iOS 客户端库说明了如何注册模板。How to Use iOS Client Library for Azure Mobile Apps shows you how to register templates.