Anteckning
Åtkomst till den här sidan kräver auktorisering. Du kan prova att logga in eller ändra kataloger.
Åtkomst till den här sidan kräver auktorisering. Du kan prova att ändra kataloger.
Översikt
I den här handledningen lägger du till push-meddelanden i snabbstartsprojektet för iOS så att ett push-meddelande skickas till enheten varje gång en post infogas.
Om du inte använder det nedladdade snabbstartsserverprojektet behöver du paketet med push-meddelandetillägget. Mer information finns i guiden Arbeta med .NET-backendserver-SDK för Azure Mobile Apps.
iOS-simulatorn stöder inte push-meddelanden. Du behöver en fysisk iOS-enhet och ett Apple Developer Program-medlemskap.
Konfigurera Notification Hub
Mobile Apps-funktionen i Azure App Service använder Azure Notification Hubs för att skicka push-meddelanden, så du konfigurerar en meddelandehubb för din mobilapp.
- I Azure-portalen går du till App Services och väljer sedan appens serverdel. Under Inställningar väljer du Push. 
- Om du vill lägga till en meddelandehubbresurs i appen väljer du Anslut. Du kan antingen skapa en hubb eller ansluta till en befintlig.   
Nu har du anslutit en meddelandehubb till ditt Mobile Apps-backend-projekt. Senare konfigurerar du den här meddelandehubben för att ansluta till ett plattformsmeddelandesystem (PNS) för att skicka till enheter.
Registrera appen för push-meddelanden
- Registrera ett app-ID för din app. Skapa ett explicit app-ID (inte ett jokerteckenapp-ID) och använd det exakta Bundle-ID som finns i ditt Xcode-snabbstartsprojekt för Bundle-ID. Det är också viktigt att du väljer alternativet Pushnotiser.
- För att förbereda för att konfigurera push-meddelanden skapar du antingen ett "Development" eller "Distribution" SSL-certifikat.
Konfigurera Azure för att skicka push-meddelanden
- Starta Nyckelringsåtkomst på mac-datorn. Öppna Mina certifikat under Kategori i det vänstra navigeringsfältet. Leta upp SSL-certifikatet som du laddade ned i föregående avsnitt och lämna sedan ut dess innehåll. Välj endast certifikatet (välj inte den privata nyckeln). Exportera den sedan.
- I Azure-portalen väljer du Bläddra bland alla>App Services. Välj sedan din Mobile Apps-serverdel.
- Under Inställningar väljer du App Service Push. Välj sedan namnet på meddelandehubben.
- Gå till Apple Push Notification Services>Uppladdningscertifikat. Ladda upp .p12-filen och välj rätt läge (beroende på om klient-SSL-certifikatet från tidigare är produktion eller sandbox-miljö). Spara eventuella ändringar.
Tjänsten är nu konfigurerad för att fungera med push-meddelanden på iOS.
Uppdatera serverdelen för att skicka push-meddelanden
.NET-backend (C#)
- Högerklicka på serverprojektet i Visual Studio och klicka på Hantera NuGet-paket, sök - Microsoft.Azure.NotificationHubsefter och klicka sedan på Installera. Då installeras Notification Hubs-biblioteket för att skicka meddelanden från serverdelen.
- Öppna Controllers>TodoItemController.cs i serverdelens Visual Studio-projekt. Lägg till följande - using-instruktion överst i filen:- using Microsoft.Azure.Mobile.Server.Config; using Microsoft.Azure.NotificationHubs;
- Ersätt metoden - PostTodoItemmed följande kod:- 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); }
- Återpublicera serverprojektet. 
Node.js backend:
- Konfigurera ditt backend-projekt. 
- Ersätt todoitem.js tabellskriptet med följande kod: - 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;
- När du redigerar filen på den lokala datorn publicerar du serverprojektet igen. 
Lägga till push-meddelanden i appen
Objective-C:
- I QSAppDelegate.m importerar du iOS SDK och QSTodoService.h: - #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h> #import "QSTodoService.h"
- I - didFinishLaunchingWithOptionsQSAppDelegate.m infogar du följande rader precis före- return YES;:- UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings]; [[UIApplication sharedApplication] registerForRemoteNotifications];
- Lägg till följande hanteringsmetoder i QSAppDelegate.m. Appen har nu uppdaterats för att stödja push-meddelanden. - // 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:
- Lägg till filen ClientManager.swift med följande innehåll. Ersätt %AppUrl% med URL:en för Azure Mobile App-serverdelen. - class ClientManager { static let sharedClient = MSClient(applicationURLString: "%AppUrl%") }
- I ToDoTableViewController.swift ersätter du raden - let clientsom initierar en- MSClientmed den här raden:- let client = ClientManager.sharedClient
- I AppDelegate.swift ersätter du brödtexten - func applicationi enligt följande:- func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings( UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)) application.registerForRemoteNotifications() return true }
- Lägg till följande hanteringsmetoder i AppDelegate.swift. Appen har nu uppdaterats för att stödja push-meddelanden. - 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) {} }
Testa push-meddelanden
- I Xcode trycker du på Kör och startar appen på en iOS-enhet (observera att push-överföring inte fungerar på simulatorer). Klicka på OK för att acceptera push-meddelanden. den här begäran inträffar första gången appen körs.
- Lägg till ett nytt objekt i appen och klicka på +.
- Kontrollera att ett meddelande har tagits emot och klicka sedan på OK för att stänga meddelandet. Nu har du framgångsrikt slutfört den här självstudien.
Mer
- Mallar ger dig flexibilitet att skicka plattformsoberoende push-meddelanden och lokaliserade push-meddelanden. Hur du använder iOS-klientbibliotek för Azure Mobile Apps visar hur du registrerar mallar.