Compartir a través de


Agregar notificaciones push a la aplicación iOS

Información general

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

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

El simulador de iOS no admite notificaciones push. Necesita un dispositivo iOS físico y una pertenencia al Programa para desarrolladores de Apple.

Configuración del centro de notificaciones

La función Mobile Apps de Azure App Service usa Azure Notification Hubs para enviar notificaciones push, por lo tanto, configurarás un centro de notificaciones para su aplicación móvil.

  1. En Azure Portal, vaya a App Servicesy, a continuación, seleccione el back-end de la aplicación. En Configuración, seleccione Notificaciones Push.

  2. Para agregar un recurso del centro de notificaciones a la aplicación, seleccionar Connect. Puede crear un centro o conectarse a uno existente.

    Configuración de un centro de conectividad

Ahora ha conectado un centro de notificaciones al proyecto de back-end de Mobile Apps. Más adelante, configure este centro de notificaciones para conectarse a un sistema de notificaciones de plataforma (PNS) para insertar en los dispositivos.

Registro de la aplicación para notificaciones push

Configuración de Azure para enviar notificaciones push

  1. En el equipo Mac, inicie acceso a llaveros. 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, a continuación, divulga su contenido. Seleccione solo el certificado (no seleccione la clave privada). A continuación, exporta .
  2. En el portal de Azure, seleccione Examinar todo>Servicios de Aplicaciones. A continuación, seleccione el back-end de Mobile Apps.
  3. En Configuración, seleccione Notificaciones Push de App Service. A continuación, seleccione el nombre del centro de notificaciones.
  4. Vaya a Apple Push Notification Services>Cargar Certificado. Cargue el archivo .p12, seleccionando el modo correcto (en función de si el certificado SSL de cliente anterior es de producción o entorno de pruebas). Guarde los cambios.

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

Actualización del back-end para enviar notificaciones push

Back-end de .NET (C#)::

  1. En Visual Studio, haga clic con el botón derecho en el proyecto de servidor y haga clic en Administrar paquetes NuGet, busque Microsoft.Azure.NotificationHubsy, a continuación, 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 Controladores>TodoItemController.cs. En la parte superior del archivo, agregue la siguiente using instrucción:

    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. Republíque el proyecto del servidor.

Node.js backend:

  1. Configure el proyecto de back-end.

  2. Reemplace el script de todoitem.js tabla 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. Al editar el archivo en el equipo local, vuelva a publicar el proyecto de servidor.

Adición de 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 QSAppDelegate.m, inserte didFinishLaunchingWithOptions 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. La aplicación ahora se actualiza para admitir 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 let client línea que inicializa una MSClient por esta línea:

    let client = ClientManager.sharedClient
    
  3. En AppDelegate.swift, reemplace el cuerpo de func application como se indica a continuación:

    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 siguientes métodos de controlador. La aplicación ahora se actualiza para admitir 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 push

  • En Xcode, presione Ejecutar e inicie la aplicación en un dispositivo iOS (tenga en cuenta que la inserción no funcionará en 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 recibe una notificación y haga clic en Aceptar para descartar la notificación. Ya ha completado correctamente este tutorial.

Más