Incorporación de notificaciones push a la aplicación iOS

Información general

En este tutorial, se agregan notificaciones push al proyecto de inicio rápido de iOS para que, cada vez que se envíe una notificación de inserción al dispositivo, se inserte un registro.

Si no usa el proyecto de servidor de inicio rápido descargado, necesitará el paquete de extensión de notificaciones push. Para más información, consulte la guía Trabajar con el SDK del servidor back-end de .NET para Azure Mobile Apps.

El simulador de iOS no admite notificaciones de inserción. Necesita un dispositivo de iOS físico y una suscripción de Apple Developer Program.

Configurar el Centro de notificaciones

La característica Mobile Apps de Azure App Service usa Azure Notification Hubs para enviar notificaciones push; por lo tanto, necesita un centro de notificaciones para su aplicación móvil.

  1. En Azure Portal, vaya a App Services y seleccione el back-end de la aplicación. En Configuración, seleccione Insertar.

  2. Seleccione Conectar para agregar un recurso de Centro de notificaciones a la aplicación. Puede crear un centro o conectarse a uno existente.

    Configurar un centro

Ya ha conectado un centro de notificaciones al proyecto de back-end de Mobile Apps. Más adelante configure este centro de notificaciones para que se conecte a un sistema de notificación de plataforma (PNS) que envíe notificaciones push a los dispositivos.

Registro de aplicaciones para notificaciones push

Configuración de Azure para enviar notificaciones push

  1. En el equipo Mac, inicie Acceso a llaves. En la barra de navegación izquierda, en Categoría, abra Mis certificados. Busque el certificado SSL que descargó en la sección anterior y muestre su contenido. Seleccione solo el certificado (no seleccione la clave privada). A continuación, expórtelo.
  2. En Azure Portal, seleccione Examinar todo>App Services. A continuación, seleccione el back-end de Mobile Apps.
  3. En Configuración, seleccione App Service Push. A continuación, seleccione el nombre del centro de notificaciones.
  4. Vaya a Apple Push Notification ServicesUpload Certificate (Cargar certificado de Apple Push Notification Services>). Cargue el archivo .p12, seleccionando el modo correcto (en función de si el certificado SSL de cliente anterior es de producción o espacio aislado). Guarde los cambios.

El servicio ahora está configurado para trabajar con las notificaciones push en iOS.

Actualizar el back-end para enviar notificaciones de inserción

Back-end de .NET (C#):

  1. En Visual Studio, haga clic con el botón derecho en el proyecto de servidor, haga clic en Administrar paquetes de NuGet, busque Microsoft.Azure.NotificationHubs y, por último, haga clic en Instalar. Esto instala la biblioteca de Notification Hubs para enviar notificaciones desde el back-end.

  2. En el proyecto de Visual Studio del back-end, abra Controllers>TodoItemController.cs. Al principio del archivo, agregue la siguiente instrucción using :

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. Reemplace el método PostTodoItem con el código siguiente:

    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. Vuelva a publicar el proyecto de servidor.

Node.js back-end:

  1. Configure el proyecto de back-end.

  2. Reemplace el script de la tabla todoitem.js por el código siguiente:

    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. Cuando edite el archivo en el equipo local, vuelva a publicar el proyecto de servidor.

Agregar notificaciones push a la aplicación

Objective-C:

  1. En QSAppDelegate.m, importe el SDK de iOS y QSTodoService.h:

    #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h>
    #import "QSTodoService.h"
    
  2. En didFinishLaunchingWithOptions, en QSAppDelegate.m, inserte las líneas siguientes justo antes de return YES;:

    UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  3. En QSAppDelegate.m, agregue los siguientes métodos de controlador. Ahora su aplicación está actualizada para que sea compatible con las notificaciones 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. Agregue el archivo ClientManager.swift con el siguiente contenido. Reemplace %AppUrl% por la dirección URL del back-end de la aplicación móvil de Azure.

    class ClientManager {
        static let sharedClient = MSClient(applicationURLString: "%AppUrl%")
    }
    
  2. En ToDoTableViewController.swift, reemplace la línea let client que inicializa un MSClient por esta línea:

    let client = ClientManager.sharedClient
    
  3. En AppDelegate.swift, reemplace el cuerpo de func application de la siguiente manera:

    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound],
                categories: nil))
        application.registerForRemoteNotifications()
        return true
    }
    
  4. En AppDelegate.swift, agregue los métodos de controlador siguientes. Ahora su aplicación está actualizada para que sea compatible con las notificaciones 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) {}
    
    }
    

Probar notificaciones de inserción

  • En Xcode, presione Ejecutar e inicie la aplicación en un dispositivo iOS (tenga en cuenta que las notificaciones push no funcionan en los simuladores). Haga clic en Aceptar para aceptar notificaciones push; esta solicitud se produce la primera vez que se ejecuta la aplicación.
  • En la aplicación, agregue un nuevo elemento y haga clic en +.
  • Compruebe que se ha recibido la notificación y, a continuación, haga clic en Aceptar para descartarla. Ya ha completado correctamente este tutorial.

Más