iOS Uygulamanıza Anında İletme Bildirimleri Ekleme

Genel Bakış

Bu öğreticide, iOS hızlı başlangıç projesine anında iletme bildirimleri ekleyerek her kayıt eklendiğinde cihaza anında iletme bildirimi gönderilmesini sağlarsınız.

İndirilen hızlı başlangıç sunucusu projesini kullanmıyorsanız anında iletme bildirimi uzantısı paketine ihtiyacınız olacaktır. Daha fazla bilgi için bkz. Azure Mobile Apps için .NET arka uç sunucusu SDK'sı ile çalışma kılavuzu.

iOS simülatörü anında iletme bildirimlerini desteklemez. Fiziksel bir iOS cihazına ve Apple Geliştirici Programı üyeliğine ihtiyacınız vardır.

Bildirim Hub'ına Yapılandırma

Azure App Service Mobile Apps özelliği, gönderim göndermek için Azure Notification Hubs'ı kullandığından, mobil uygulamanız için bir bildirim hub'ı yapılandıracaksınız.

  1. Azure portalApp Services'e gidin ve uygulamanızın arka ucunu seçin. Ayarlar'ın altında Gönder'i seçin.

  2. Uygulamaya bildirim hub'ı kaynağı eklemek için Bağlan'ı seçin. Hub oluşturabilir veya mevcut bir hub'a bağlanabilirsiniz.

    Hub yapılandırma

Artık Mobile Apps arka uç projenize bir bildirim hub'ı bağladınız. Daha sonra bu bildirim hub'sını cihazlara göndermek üzere bir platform bildirim sistemine (PNS) bağlanacak şekilde yapılandıracaksınız.

Uygulamayı anında iletme bildirimleri için kaydetme

Azure'ı anında iletme bildirimleri gönderecek şekilde yapılandırma

  1. Mac bilgisayarınızda Anahtarlık Erişimi'ni başlatın. Sol gezinti çubuğundaki Kategori'nin altında Sertifikalarım'ı açın. Önceki bölümde indirdiğiniz SSL sertifikasını bulun ve içeriğini açıklayın. Yalnızca sertifikayı seçin (özel anahtarı seçmeyin). Ardından dışarı aktarın.
  2. Azure portal Tüm >Uygulama HizmetlerineGözat'ıseçin. Ardından Mobile Apps arka ucunuzu seçin.
  3. Ayarlar'ın altında App Service Gönder'i seçin. Ardından bildirim hub'ınızın adını seçin.
  4. Apple Anında İletme Bildirimi Hizmetleri>Sertifikayı Karşıya Yükle'ye gidin. Doğru Modu seçerek .p12 dosyasını karşıya yükleyin (önceki istemci SSL sertifikanızın üretim veya korumalı alan olmasına bağlı olarak). Değişiklikleri kaydedin.

Hizmetiniz artık iOS'ta anında iletme bildirimleriyle çalışacak şekilde yapılandırılmıştır.

Anında iletme bildirimleri göndermek için arka ucu güncelleştirme

.NET arka ucu (C#):

  1. Visual Studio'da sunucu projesine sağ tıklayın ve NuGet Paketlerini Yönet'e tıklayın, araması yapın Microsoft.Azure.NotificationHubsve Yükle'ye tıklayın. Bu, arka ucunuzdan bildirim göndermek için Notification Hubs kitaplığını yükler.

  2. Arka ucun Visual Studio projesinde Controllers>TodoItemController.cs dosyasını açın. Dosyanın en üstüne aşağıdaki using deyimi ekleyin:

    using Microsoft.Azure.Mobile.Server.Config;
    using Microsoft.Azure.NotificationHubs;
    
  3. PostTodoItem yöntemini aşağıdaki kod ile değiştirin:

    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. Sunucu projesini yeniden yayımlayın.

Arka ucuNode.js:

  1. Arka uç projenizi ayarlayın.

  2. todoitem.js tablo betiğini aşağıdaki kodla değiştirin:

    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. Dosyayı yerel bilgisayarınızda düzenlerken sunucu projesini yeniden yayımlayın.

Uygulamaya anında iletme bildirimleri ekleme

Objective-C:

  1. QSAppDelegate.m'de iOS SDK'sını ve QSTodoService.h dosyasını içeri aktarın:

    #import <MicrosoftAzureMobile/MicrosoftAzureMobile.h>
    #import "QSTodoService.h"
    
  2. didFinishLaunchingWithOptionsQSAppDelegate.m dosyasında, aşağıdaki satırları hemen önüne return YES;ekleyin:

    UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  3. QSAppDelegate.m dosyasına aşağıdaki işleyici yöntemlerini ekleyin. Uygulamanız artık anında iletme bildirimlerini destekleyecek şekilde güncelleştirildi.

    // 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. ClientManager.swift dosyasını aşağıdaki içeriklere ekleyin. %AppUrl% değerini Azure Mobil Uygulama arka ucu URL'si ile değiştirin.

    class ClientManager {
        static let sharedClient = MSClient(applicationURLString: "%AppUrl%")
    }
    
  2. ToDoTableViewController.swift dosyasında, öğesini MSClient başlatan satırı şu satırla değiştirinlet client:

    let client = ClientManager.sharedClient
    
  3. AppDelegate.swift dosyasında gövdesini func application aşağıdaki gibi değiştirin:

    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound],
                categories: nil))
        application.registerForRemoteNotifications()
        return true
    }
    
  4. AppDelegate.swift'te aşağıdaki işleyici yöntemlerini ekleyin. Uygulamanız artık anında iletme bildirimlerini destekleyecek şekilde güncelleştirildi.

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

Anında iletme bildirimlerini test edin

  • Xcode'da Çalıştır'a basın ve uygulamayı bir iOS cihazında başlatın (gönderimin simülatörlerde çalışmayacağını unutmayın). Anında iletme bildirimlerini kabul etmek için Tamam'a tıklayın; bu istek, uygulama ilk kez çalıştırıldığında gerçekleşir.
  • Uygulamada yeni bir öğe ekleyin ve öğesine tıklayın +.
  • Bir bildirimin alındığını doğrulayın, ardından bildirimi kapatmak için Tamam'a tıklayın. Bu öğreticiyi başarıyla tamamladınız.

Daha fazla