Pushmeldingen toevoegen aan uw iOS-app

Overzicht

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

Als u het gedownloade quickstartserverproject niet gebruikt, hebt u het pakket voor pushmeldingen nodig. Zie De handleiding Werken met de .NET-back-endserver-SDK 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. U gaat dus een Notification Hub configureren voor uw mobiele app.

  1. Ga in de Azure Portal naar App Services en selecteer vervolgens de back-end van uw app. Selecteer Push onder Instellingen.

  2. Als u een Notification Hub-resource aan de app wilt toevoegen, 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 van Mobile Apps. Later configureert u deze Notification Hub om verbinding te maken met een PNS (Platform Notification System) om naar apparaten te pushen.

App registreren voor pushmeldingen

  • Registreer een app-id voor uw app. Maak een expliciete app-id (geen app-id met jokertekens) en gebruik voor bundel-id de exacte bundel-id die zich in uw Xcode-quickstartproject bevindt. Het is ook van cruciaal belang dat u de optie Pushmeldingen selecteert.
  • Maak vervolgens een SSL-certificaat voor ontwikkeling of distributie om pushmeldingen te configureren.

Azure configureren voor het verzenden van pushmeldingen

  1. Start op uw Mac Keychain Access. Open Mijn certificaten op de linkernavigatiebalk onder Categorie. Zoek het SSL-certificaat dat u in de vorige sectie hebt gedownload en geef de inhoud ervan weer. Selecteer alleen het certificaat (selecteer de persoonlijke sleutel niet). Exporteer het vervolgens.
  2. Selecteer In de Azure Portalde optie Bladeren in alle>App Services. Selecteer vervolgens de back-end van Mobile Apps.
  3. Selecteer onder InstellingenApp Service Push. Selecteer vervolgens de naam van uw Notification Hub.
  4. Ga naar hetuploadcertificaat van Apple Push Notification Services>. Upload het .p12-bestand en selecteer de juiste modus (afhankelijk van of uw client-SSL-certificaat van eerder productie of sandbox is). Sla eventuele wijzigingen op.

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

Back-end bijwerken om pushmeldingen te verzenden

.NET-back-end (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 bovenaan 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 die een MSClient door deze regel initialiseert:

    let client = ClientManager.sharedClient
    
  3. Vervang in AppDelegate.swift de hoofdtekst als func application 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 op simulators). Klik op OK om pushmeldingen te accepteren; deze aanvraag treedt op 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