Přidání nabízených oznámení do aplikace pro iOS

Přehled

V tomto kurzu přidáte nabízená oznámení do projektu rychlého startu pro iOS , aby se nabízené oznámení odeslalo do zařízení při každém vložení záznamu.

Pokud stažený projekt serveru rychlý start nepoužíváte, budete potřebovat balíček rozšíření nabízených oznámení. Další informace najdete v tématu Práce se sadou SDK back-endového serveru .NET pro Azure Mobile Apps .

Simulátor iOS nepodporuje nabízená oznámení. Potřebujete fyzické zařízení s iOSem a členství v programu Apple Developer Program.

Konfigurace centra oznámení

Funkce Mobile Apps Azure App Service používá službu Azure Notification Hubs k odesílání nabízených oznámení, takže pro mobilní aplikaci nakonfigurujete centrum oznámení.

  1. V Azure Portal přejděte do App Services a pak vyberte back-end vaší aplikace. V části Nastavení vyberte Nabízená oznámení.

  2. Pokud chcete do aplikace přidat prostředek centra oznámení, vyberte Připojit. Můžete buď vytvořit centrum, nebo se připojit k existujícímu.

    Konfigurace centra

Teď jste připojili centrum oznámení k back-endovém projektu Mobile Apps. Později nakonfigurujete toto centrum oznámení tak, aby se připojilo k systému oznámení platformy (PNS) pro nabízení do zařízení.

Registrace aplikace pro nabízená oznámení

Konfigurace Azure pro odesílání nabízených oznámení

  1. Na Macu spusťte Keychain Access. Na levém navigačním panelu v části Kategorie otevřete Moje certifikáty. Najděte certifikát SSL, který jste si stáhli v předchozí části, a pak zpřístupňte jeho obsah. Vyberte pouze certifikát (nevybírejte privátní klíč). Pak ho exportujte.
  2. V Azure Portal vyberte Procházet všechny>služby App Services. Pak vyberte back-end Mobile Apps.
  3. V části Nastavení vyberte App Service Nabízené oznámení. Pak vyberte název centra oznámení.
  4. Přejděte naCertifikát nahráníslužby Apple Push Notification Services>. Nahrajte soubor .p12 a vyberte správný režim (v závislosti na tom, jestli je váš klientský certifikát SSL z dřívější verze produkční nebo sandbox). Uložte všechny změny.

Vaše služba je teď nakonfigurovaná tak, aby fungovala s nabízenými oznámeními v iOSu.

Aktualizace back-endu pro odesílání nabízených oznámení

Back-end .NET (C#):

  1. V sadě Visual Studio klikněte pravým tlačítkem myši na projekt serveru a klikněte na Spravovat balíčky NuGet, vyhledejte Microsoft.Azure.NotificationHubsa klikněte na nainstalovat. Tím se nainstaluje knihovna Notification Hubs pro odesílání oznámení z back-endu.

  2. V projektu sady Visual Studio back-endu otevřete Controllers>TodoItemController.cs. V horní části souboru přidejte následující using příkaz:

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. Nahraďte metodu PostTodoItem následujícím kódem:

    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. Znovu publikujte projekt serveru.

Back-end Node.js:

  1. Nastavení back-endového projektu

  2. Nahraďte skript tabulky todoitem.js následujícím kódem:

    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. Při úpravách souboru na místním počítači znovu publikujte serverový projekt.

Přidání nabízených oznámení do aplikace

Objective-C:

  1. V QSAppDelegate.m naimportujte sadu SDK pro iOS a QSTodoService.h:

    #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h>
    #import "QSTodoService.h"
    
  2. V didFinishLaunchingWithOptionsQSAppDelegate.m vložte následující řádky přímo před return YES;:

    UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  3. V QSAppDelegate.m přidejte následující metody obslužné rutiny. Vaše aplikace se teď aktualizuje tak, aby podporovala nabízená oznámení.

    // 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. Přidejte soubor ClientManager.swift s následujícím obsahem. Nahraďte %AppUrl% adresou URL back-endu mobilní aplikace Azure.

    class ClientManager {
        static let sharedClient = MSClient(applicationURLString: "%AppUrl%")
    }
    
  2. V toDoTableViewController.swift nahraďte let client řádek, který inicializuje MSClient tento řádek:

    let client = ClientManager.sharedClient
    
  3. V AppDelegate.swift nahraďte text func application následujícím způsobem:

    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound],
                categories: nil))
        application.registerForRemoteNotifications()
        return true
    }
    
  4. V AppDelegate.swift přidejte následující metody obslužné rutiny. Vaše aplikace se teď aktualizuje tak, aby podporovala nabízená oznámení.

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

Testování nabízených oznámení

  • V Xcode stiskněte Spustit a spusťte aplikaci na zařízení s iOSem (všimněte si, že nabízená oznámení nebudou fungovat na simulátorech). Kliknutím na tlačítko OK přijmete nabízená oznámení; k tomuto požadavku dochází při prvním spuštění aplikace.
  • V aplikaci přidejte novou položku a klikněte na +.
  • Ověřte, že je oznámení přijato, a kliknutím na tlačítko OK oznámení zavřete. Nyní jste úspěšně dokončili tento kurz.

Víc