共用方式為


將推播通知新增至您的 iOS 應用程式

概觀

在本教學課程中,您會將推播通知新增至 iOS 快速入門專案,以便在每次插入一筆記錄時傳送推播通知至裝置。

如果您不要使用下載的快速入門伺服器專案,則需要推播通知擴充套件。 如需詳細資訊,請參閱使用適用於 Azure Mobile Apps 的 .NET 後端伺服器 SDK 指南。

iOS 模擬器不支援推播通知。 您需要實體 iOS 裝置和 Apple Developer Program 成員資格

設定通知中樞

Azure App Service 的 Mobile Apps 使用 Azure 通知中樞來傳送推送,因此您將為行動應用程式設定通知中樞。

  1. Azure 入口網站中,移至 [應用程式服務],然後選取應用程式後端。 在 [設定] 底下,選取 [推播]

  2. 將通知中樞資源新增至應用程式,選取 [連線]。 您可以建立中樞或連線到現有的中樞。

    設定中樞

現在您已將通知中樞連接到 Mobile Apps 後端專案。 稍後您要設定此通知中樞,使其連線到平台通知系統 (PNS) 以推播至裝置。

註冊應用程式以取得推播通知

設定 Azure 來傳送推播通知

  1. 在您的 Mac 上啟動 Keychain Access。 在左側導覽列的 [類別] 下,開啟 [我的憑證]。 尋找您在上一節中下載的 SSL 憑證,然後公開其內容。 僅選取憑證 (不選取私密金鑰)。 然後將它匯出
  2. Azure 入口網站中,選取 [瀏覽全部]>[應用程式服務]。 然後選取您的 Mobile Apps 後端。
  3. 在 [設定] 下,選取 [App Service 推播]。 然後選取您的通知中樞名稱。
  4. 移至Apple 推播通知服務>上傳憑證。 上傳 .p12 檔案,選取正確的模式 (根據您稍早的用戶端 SSL 憑證為生產或沙箱)。 儲存任何變更。

您的服務現在已設定成在 iOS 上使用推播通知。

更新後端程式碼以傳送推播通知

.NET 後端 (C#)

  1. 在 Visual Studio 中,以滑鼠右鍵按一下伺服器專案並按一下 [管理 NuGet 封裝],搜尋 Microsoft.Azure.NotificationHubs,然後按一下 [安裝]。 這會安裝通知中樞程式庫,以便從後端傳送通知。

  2. 在後端的 Visual Studio 專案中,開啟Controllers>TodoItemController.cs。 在檔案頂端新增下列 using 陳述式:

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. 以下列程式碼取代 PostTodoItem 方法:

    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. 發佈伺服器專案。

Node.js後端

  1. 設定後端專案。

  2. 使用下列程式碼取代 todoitem.js 資料表指令碼:

    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. 當您在本機電腦上編輯檔案時,請重新發佈伺服器專案。

將推播通知新增至應用程式

Objective-C

  1. QSAppDelegate.m 中,匯入 iOS SDK 和 QSTodoService.h

    #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h>
    #import "QSTodoService.h"
    
  2. QSAppDelegate.mdidFinishLaunchingWithOptions 中,於 return YES; 之前插入下列幾行:

    UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  3. QSAppDelegate.m中,新增下列處理常式方法。 您的應用程式現在已更新為支援推播通知。

    // 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

  1. 新增含有以下內容的檔案 ClientManager.swift 。 使用 Azure 行動應用程式後端的 URL 取代 %AppUrl%

    class ClientManager {
        static let sharedClient = MSClient(applicationURLString: "%AppUrl%")
    }
    
  2. ToDoTableViewController.swift 中,將初始化 MSClientlet client 行取代為這一行:

    let client = ClientManager.sharedClient
    
  3. AppDelegate.swift,將 func application 的主體取代為:

    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中,新增下列處理常式方法。 您的應用程式現在已更新為支援推播通知。

    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) {}
    
    }
    

測試推播通知

  • 在 Xcode 中按下 [執行],並在 iOS 裝置上啟動應用程式 (請注意,推播在模擬器上無法運作)。 按一下 [確定] 以接受推播通知 (第一次執行應用程式時會發生此要求)。
  • 在應用程式中新增項目,然後按一下 +
  • 確認已收到通知,然後按一下 [ 確定 ] 以關閉通知。 您現在已成功完成此教學課程。

其他