Aggiungere notifiche push all'app iOS

Panoramica

In questa esercitazione vengono aggiunte notifiche push al progetto avvio rapido di iOS, in modo che una notifica push venga inviata al dispositivo a ogni inserimento di record.

Se non si usa il progetto server di avvio rapido scaricato, sarà necessario aggiungere il pacchetto di estensione di notifica push. Per altre informazioni, vedere Usare l'SDK del server back-end .NET per App per dispositivi mobili di Azure.

Il simulatore iOS non supporta le notifiche push. È necessario un dispositivo iOS fisico e un'appartenenza all'Apple Developer Program.

Configurare un hub di notifica

Poiché le funzioni delle app per dispositivi mobili del Servizio app di Azure usano Hub di notifica di Azure per inviare push, si dovrà configurare un hub di notifica per l'app per dispositivi mobili.

  1. Nel portale di Azure passare a Servizi app e quindi selezionare il back-end dell'app. In Impostazioni selezionare Push.

  2. Per aggiungere una risorsa hub di notifica all'app selezionare Connetti. È possibile creare un hub o connettersi a uno esistente.

    Configurare un hub

A questo punto un hub di notifica è stato connesso al progetto di back-end dell'app per dispositivi mobili. In seguito si configurerà questo hub di notifica per la connessione a un sistema PNS (Platform Notification System) per eseguire il push ai dispositivi.

f

Configurare Azure per l'invio di notifiche push

  1. In Mac avviare Keychain Access. Aprire My Certificates (Certificati personali) in Categoria nella barra di spostamento sinistra. Trovare il certificato SSL scaricato nella sezione precedente e quindi divulgarne il contenuto. Selezionare solo il certificato (non la chiave privata), quindi esportarlo.
  2. Nel portale di Azure selezionare Esplora tutto>Servizi app. Selezionare quindi il back-end di App per dispositivi mobili.
  3. In Impostazioni selezionare App Service Push (Push servizio app). Selezionare quindi il nome dell'hub di notifica.
  4. Passare a Apple Push Notification Services>Upload Certificate (Carica certificato). Caricare il file con estensione p12, selezionando la modalità corretta, a seconda che il certificato SSL client di prima sia di produzione o sandbox. Salvare le modifiche.

Il servizio è ora configurato per l'uso con le notifiche push in iOS.

Aggiornare il codice back-end per l'invio di notifiche push

Back-end .NET (C#):

  1. In Visual Studio fare clic con il pulsante destro del mouse sul progetto server, quindi scegliere Gestisci pacchetti NuGet, cercare Microsoft.Azure.NotificationHubs e infine fare clic su Installa. Consente di installare la libreria di hub di notifica per l'invio di notifiche dal back-end.

  2. Nel progetto visual Studio del back-end aprire Controllers>TodoItemController.cs. Aggiungere le istruzioni using seguenti all'inizio del file:

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. Sostituire il metodo PostTodoItem con il codice seguente:

    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. Pubblicare di nuovo il progetto server.

Node.js back-end:

  1. Configurare il progetto back-end.

  2. Sostituire lo script di tabella todoitem.js con il codice seguente:

    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. Quando si modifica il file nel computer locale, ripubblicare il progetto server.

ss

Objective-C:

  1. In QSAppDelegate.m importare iOS SDK e QSTodoService.h:

    #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h>
    #import "QSTodoService.h"
    
  2. In didFinishLaunchingWithOptions in QSAppDelegate.m inserire le righe seguenti prima di return YES;:

    UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  3. In QSAppDelegate.m aggiungere i metodi del gestore seguenti. L'app è ora aggiornata per il supporto delle notifiche 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. Aggiungere il file ClientManager.swift con i seguenti contenuti. Sostituire %AppUrl% con l'URL del back-end di app per dispositivi mobili di Azure.

    class ClientManager {
        static let sharedClient = MSClient(applicationURLString: "%AppUrl%")
    }
    
  2. In ToDoTableViewController.swift sostituire la riga let client che inizializza un MSClient con la riga seguente:

    let client = ClientManager.sharedClient
    
  3. In AppDelegate.swift sostituire il corpo di func application come indicato di seguito:

    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound],
                categories: nil))
        application.registerForRemoteNotifications()
        return true
    }
    
  4. In AppDelegate.swift, aggiungere i metodi del gestore seguenti. L'app è ora aggiornata per il supporto delle notifiche 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) {}
    
    }
    

Notifiche push di prova

  • In Xcode premere Esegui e avviare l'app in un dispositivo iOS. Si noti che il push non funzionerà nei simulatori. Fare clic su OK per accettare le notifiche push. Questa richiesta si verifica alla prima esecuzione dell'app.
  • Nell'app aggiungere un nuovo elemento e fare clic su +.
  • Verificare che venga ricevuta una notifica, quindi fare clic su OK per ignorare la notifica. L'esercitazione è stata completata.

Più informazioni