Ajout de notifications Push à votre application iOS

Vue d’ensemble

Dans ce didacticiel, vous ajoutez des notifications Push au projet Démarrage rapide iOS pour qu’une notification Push soit envoyée chaque fois qu’un enregistrement est inséré.

Si vous n’utilisez pas le projet de serveur du démarrage rapide téléchargé, vous devez ajouter le package d’extension de notification Push. Pour plus d’informations, consultez le guide Utiliser le kit SDK du serveur backend .NET pour Azure Mobile Apps.

Le simulateur iOS ne prend pas en charge les notifications Push. Vous avez besoin d’un appareil iOS physique et d’une appartenance au programme pour développeurs Apple.

Configurer un hub de notification

La fonctionnalité Mobile Apps d’Azure App Service utilise Azure Notification Hubs pour envoyer des notifications Push ; vous allez donc devoir configurer un hub de notification pour votre application mobile.

  1. Dans le portail Azure, accédez à App Services, puis sélectionnez votre serveur principal d’applications. Sous Paramètres, sélectionnez Notifications push.

  2. Pour ajouter une ressource de Hub de notification à l’application, sélectionnez Connecter. Vous pouvez créer un concentrateur ou vous connecter à un autre existant.

    Configurer un Hub

Vous avez désormais connecté un hub de notification à votre projet de serveur principal Mobile Apps. Plus tard, vous allez configurer ce Hub de notification pour qu’il se connecte à un système PNS (Platform Notification System) qui envoie des notifications Push aux appareils.

Inscrire une application pour les notifications Push

Configurer Azure pour l’envoi de notifications Push

  1. Sur votre Mac, démarrez Trousseau d’accès. Dans la barre de navigation gauche, sous Catégorie, ouvrez Mes certificats. Recherchez le certificat SSL que vous avez téléchargé à la section précédente, puis affichez son contenu. Sélectionnez uniquement le certificat (sans la clé privée). Puis exportez-le.
  2. Dans le portail Azure, sélectionnez Parcourir tout>App Services. Puis sélectionnez votre serveur principal Mobile Apps.
  3. Sous Paramètres, sélectionnez App Service Push (Notification Push App Service). Ensuite, sélectionnez le nom de votre Hub de notification.
  4. Accédez aucertificat de chargement des services> de notification Push Apple. Chargez le fichier .p12 en sélectionnant le mode approprié (en fonction du type de votre certificat SSL client précédemment utilisé : Production ou Sandbox). Enregistrez les modifications.

Votre service est désormais configuré et prêt à fonctionner avec les notifications Push sur iOS.

Mettre à jour le serveur principal pour l'envoi de notifications push

Serveur principal .NET (C#):

  1. Dans Visual Studio, cliquez avec le bouton droit sur le projet de serveur, puis cliquez sur Gérer les packages NuGet, recherchez Microsoft.Azure.NotificationHubs et cliquez sur Installer. Cette opération installe la bibliothèque Notification Hubs pour l’envoi de notifications à partir de votre serveur principal.

  2. Dans le projet Visual Studio du back-end, ouvrez Controllers>TodoItemController.cs. Au début du fichier, ajoutez l’instruction using suivante :

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. Remplacez la méthode PostTodoItem par le code suivant :

    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. Publier à nouveau le projet de serveur

Node.js back-end :

  1. Configurez votre projet back-end.

  2. Remplacez le script de la table todoitem.js par le code suivant :

    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. Quand vous modifiez le fichier sur votre ordinateur local, republiez le projet serveur.

Ajouter des notifications Push à l’application

Objective-C :

  1. Dans QSAppDelegate.m, importez le Kit de développement logiciel (SDK) iOS ainsi que QSTodoService.h :

    #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h>
    #import "QSTodoService.h"
    
  2. Dans didFinishLaunchingWithOptions de QSAppDelegate.m, insérez les lignes suivantes juste avant return YES; :

    UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  3. Dans QSAppDelegate.m, ajoutez les méthodes de gestionnaire suivantes. L'application est mise à jour et prend en charge les notifications Push.

    // 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. Ajoutez le fichier ClientManager.swift avec le contenu suivant. Remplacez %AppUrl% par l’URL du serveur principal Azure Mobile App.

    class ClientManager {
        static let sharedClient = MSClient(applicationURLString: "%AppUrl%")
    }
    
  2. Dans ToDoTableViewController.swift, remplacez la ligne let client chargée d’initialiser un MSClient par cette ligne :

    let client = ClientManager.sharedClient
    
  3. Dans AppDelegate.swift, remplacez le corps de func application comme suit :

    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound],
                categories: nil))
        application.registerForRemoteNotifications()
        return true
    }
    
  4. Dans AppDelegate.swift, ajoutez les méthodes de gestionnaire suivantes. L'application est mise à jour et prend en charge les notifications Push.

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

Tester les notifications Push

  • Dans Xcode, appuyez sur Exécuter et démarrez l’application sur un appareil iOS (notez que le push ne fonctionnera pas sur les simulateurs). Cliquez sur OK pour accepter explicitement les notifications push ; cette requête se produit à la première exécution de l’application.
  • Dans l’application, ajoutez un nouvel élément et cliquez sur +.
  • Vérifiez qu’une notification est reçue, puis cliquez sur OK pour ignorer la notification. Ce didacticiel est maintenant terminé.

Plus