Delen via


Pushmeldingen toevoegen aan uw iOS-app

Overzicht

In deze zelfstudie voegt u pushmeldingen toe aan het iOS-quickstartproject , zodat een pushmelding naar het apparaat wordt verzonden telkens wanneer een record wordt ingevoegd.

Als u het gedownloade quickstart-serverproject niet gebruikt, hebt u het pushmeldingsuitbreidingspakket nodig. Zie de handleiding Werken met de SDK voor de .NET-back-endserver voor Azure Mobile Apps voor meer informatie.

De iOS-simulator biedt geen ondersteuning voor pushmeldingen. U hebt een fysiek iOS-apparaat en een Apple Developer Program-lidmaatschap nodig.

Notification Hub configureren

De functie Mobile Apps van Azure App Service maakt gebruik van Azure Notification Hubs om pushes te verzenden, zodat u een Notification Hub configureert voor uw mobiele app.

  1. Ga in de Azure Portalnaar App Services-en selecteer vervolgens de back-end van uw app. Selecteer onder Instellingende optie Push.

  2. Om een meldingshubbron aan de app toe te voegen, selecteert u Verbinding maken. U kunt een hub maken of verbinding maken met een bestaande hub.

    een hub configureren

U hebt nu een Notification Hub verbonden met uw back-endproject voor Mobiele apps. Later configureert u deze Notification Hub om verbinding te maken met een platformmeldingssysteem (PNS) om naar apparaten te pushen.

App registreren voor pushmeldingen

Azure configureren voor het verzenden van pushmeldingen

  1. Open op uw Mac Sleutelhangertoegang. Open in de linkernavigatiebalk, onder Categorie, Mijn certificaten. Zoek het SSL-certificaat dat u in de vorige sectie hebt gedownload en geef de inhoud ervan weer. Selecteer alleen het certificaat (selecteer niet de persoonlijke sleutel). Vervolgens hetexporteren.
  2. Selecteer in de Azure portal, Alles weergeven>App Services. Selecteer vervolgens de back-end van uw Mobile Apps.
  3. Selecteer onder Instellingen, App Service Push. Selecteer vervolgens de naam van de Notification Hub.
  4. Ga naar Apple Push Notification Services>Certificaat uploaden. Upload het .p12-bestand en selecteer de juiste modus (afhankelijk van of uw ssl-clientcertificaat van eerder productie of sandbox is). Sla eventuele wijzigingen op.

Uw service is nu geconfigureerd voor gebruik met pushmeldingen op iOS.

Back-end bijwerken om pushmeldingen te verzenden

.NET-backend (C#):

  1. Klik in Visual Studio met de rechtermuisknop op het serverproject en klik op NuGet-pakketten beheren, zoek naar Microsoft.Azure.NotificationHubsen klik vervolgens op Installeren. Hiermee installeert u de Notification Hubs-bibliotheek voor het verzenden van meldingen vanuit uw back-end.

  2. Open Controllers>TodoItemController.cs in het Visual Studio-project van de back-end. Voeg boven aan het bestand de volgende using instructie toe:

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. Vervang de PostTodoItem methode door de volgende code:

    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. Publiceer het serverproject opnieuw.

Node.js back-end:

  1. Stel uw back-endproject in.

  2. Vervang het todoitem.js tabelscript door de volgende code:

    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. Wanneer u het bestand op uw lokale computer bewerkt, publiceert u het serverproject opnieuw.

Pushmeldingen toevoegen aan app

Objective-C:

  1. Importeer in QSAppDelegate.m de iOS SDK en QSTodoService.h:

    #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h>
    #import "QSTodoService.h"
    
  2. Voeg didFinishLaunchingWithOptions in QSAppDelegate.m de volgende regels vóór return YES;in:

    UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  3. Voeg in QSAppDelegate.m de volgende handlermethoden toe. Uw app is nu bijgewerkt ter ondersteuning van pushmeldingen.

    // 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. Voeg bestand ClientManager.swift toe met de volgende inhoud. Vervang %AppUrl% door de URL van de back-end van de mobiele Azure-app.

    class ClientManager {
        static let sharedClient = MSClient(applicationURLString: "%AppUrl%")
    }
    
  2. Vervang in ToDoTableViewController.swift de let client regel waarmee een MSClient regel wordt geïnitialiseerd door deze regel:

    let client = ClientManager.sharedClient
    
  3. Vervang in AppDelegate.swift de inhoud als volgt:

    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound],
                categories: nil))
        application.registerForRemoteNotifications()
        return true
    }
    
  4. Voeg in AppDelegate.swift de volgende handlermethoden toe. Uw app is nu bijgewerkt ter ondersteuning van pushmeldingen.

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

Pushmeldingen testen

  • Druk in Xcode op Uitvoeren en start de app op een iOS-apparaat (houd er rekening mee dat push niet werkt in simulators). Klik op OK om pushmeldingen te accepteren; deze aanvraag vindt plaats wanneer de app voor het eerst wordt uitgevoerd.
  • Voeg in de app een nieuw item toe en klik op +.
  • Controleer of er een melding is ontvangen en klik vervolgens op OK om de melding te sluiten. U hebt deze zelfstudie nu voltooid.

Meer