Menambahkan notifikasi push ke Aplikasi Xamarin.iOS Anda

Gambaran Umum

Dalam tutorial ini, Anda menambahkan pemberitahuan push ke proyek mulai cepat Xamarin.iOS sehingga pemberitahuan push dikirim ke perangkat setiap kali rekaman dimasukkan.

Jika Anda tidak menggunakan proyek server mulai cepat yang diunduh, Anda memerlukan paket ekstensi pemberitahuan push. Lihat Bekerja dengan SDK server backend .NET untuk Azure Mobile Apps untuk informasi selengkapnya.

Prasyarat

  • Selesaikan tutorial mulai cepat Xamarin.iOS .
  • Perangkat iOS fisik. Notifikasi push tidak didukung oleh simulator iOS.

Mendaftarkan aplikasi untuk pemberitahuan push di portal pengembang Apple

Mengonfigurasi Aplikasi Seluler Anda untuk mengirim pemberitahuan push

  1. Di Mac Anda, luncurkan Akses Rantai Kunci. Di bilah navigasi kiri, di bawah Kategori, buka Sertifikat Saya. Temukan sertifikat SSL yang Anda unduh di bagian sebelumnya, lalu ungkapkan isinya. Pilih hanya sertifikat (jangan pilih kunci pribadi). Kemudian ekspor.
  2. Di portal Azure, pilih TelusuriLayanan AllApp>. Kemudian pilih kembali Aplikasi Seluler Anda.
  3. Di bawah Pengaturan, pilih App Service Push. Kemudian pilih nama hub notifikasi Anda.
  4. Buka Layanan >Pemberitahuan Push AppleUpload Sertifikat. Upload file .p12, memilih Mode yang benar (tergantung pada apakah sertifikat SSL klien Anda dari yang lebih awal adalah produksi atau kotak pasir). Simpan perubahan apa pun.

Layanan Anda sekarang dikonfigurasi untuk bekerja dengan pemberitahuan push di iOS.

Memperbarui proyek server untuk mengirim pemberitahuan push

Di bagian ini, Anda memperbarui kode di proyek back-end Aplikasi Seluler yang ada untuk mengirim pemberitahuan push setiap kali item baru ditambahkan. Proses ini didukung oleh fitur template Azure Notification Hubs, yang memungkinkan dorongan lintas platform. Berbagai klien terdaftar untuk pemberitahuan push menggunakan template, dan satu dorongan universal bisa sampai ke semua platform klien.

Pilih salah satu prosedur berikut yang cocok dengan jenis proyek back-end Anda— back end .NET atau Node.js back end.

Proyek back-end .NET

  1. Di Visual Studio, klik kanan proyek server. Kemudian pilih Kelola Paket NuGet. Cari Microsoft.Azure.NotificationHubs, kemudian pilih Instal. Proses ini menginstal pustaka Notification Hubs untuk mengirim pemberitahuan dari ujung belakang.

  2. Dalam proyek server, buka ControllersTodoItemController>.cs. Kemudian tambahkan yang berikut menggunakan pernyataan:

    using System.Collections.Generic;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Azure.Mobile.Server.Config;
    
  3. Dalam metode PostTodoItem , tambahkan kode berikut setelah panggilan ke InsertAsync:

    // 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);
    
    // Send the message so that all template registrations that contain "messageParam"
    // receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
    Dictionary<string,string> templateParams = new Dictionary<string,string>();
    templateParams["messageParam"] = item.Text + " was added to the list.";
    
    try
    {
        // Send the push notification and log the results.
        var result = await hub.SendTemplateNotificationAsync(templateParams);
    
        // 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");
    }
    

    Proses ini mengirimkan pemberitahuan template yang berisi item. Teks saat item baru disisipkan.

  4. Terbitkan ulang proyek server.

Node.js proyek back-end

  1. Siapkan proyek backend Anda.

  2. Ganti kode yang ada di todoitem.js dengan kode berikut:

    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();
    
    table.insert(function (context) {
    // For more information about the Notification Hubs JavaScript SDK,
    // see https://aka.ms/nodejshubs.
    logger.info('Running TodoItem.insert');
    
    // Define the template payload.
    var payload = '{"messageParam": "' + context.item.text + '" }';  
    
    // Execute the insert. The insert returns the results as a promise.
    // Do the push as a post-execute action within the promise flow.
    return context.execute()
        .then(function (results) {
            // Only do the push if configured.
            if (context.push) {
                // Send a template notification.
                context.push.send(null, payload, function (error) {
                    if (error) {
                        logger.error('Error while sending push notification: ', error);
                    } else {
                        logger.info('Push notification sent successfully!');
                    }
                });
            }
            // Don't forget to return the results from the context.execute().
            return results;
        })
        .catch(function (error) {
            logger.error('Error while running context.execute: ', error);
        });
    });
    
    module.exports = table;  
    

    Proses ini mengirimkan pemberitahuan template yang berisi item.text saat item baru dimasukkan.

  3. Saat Anda mengedit file di komputer lokal Anda, terbitkan kembali proyek server.

Mengonfigurasi proyek Xamarin.iOS Anda

Mengonfigurasi proyek iOS di Xamarin Studio

  1. Di Xamarin.Studio, buka Info.plist, dan perbarui Bundle Identifier dengan ID bundel yang Anda buat sebelumnya dengan ID aplikasi baru Anda.

  2. Gulir ke bawah ke Mode Latar Belakang. Pilih kotak Aktifkan Mode Latar Belakang dan kotak Pemberitahuan jarak jauh .

  3. Klik dua kali proyek Anda di Panel Solusi untuk membuka Opsi Project.

  4. Di bawah Build, pilih Penandatanganan Bundel iOS, dan pilih identitas dan profil provisi yang sesuai yang baru saja Anda siapkan untuk proyek ini.

    Ini memastikan bahwa proyek menggunakan profil baru untuk penandatanganan kode. Untuk dokumentasi penyediaan perangkat Xamarin resmi, lihat Penyediaan Perangkat Xamarin.

Mengonfigurasi proyek iOS di Visual Studio

  1. Di Visual Studio, klik kanan proyek, lalu klik Properti.

  2. Di halaman properti, klik tab Aplikasi iOS , dan perbarui Identifier dengan ID yang Anda buat sebelumnya.

  3. Di tab Penandatanganan Bundel iOS , pilih identitas dan profil provisi yang sesuai yang baru saja Anda siapkan untuk proyek ini.

    Ini memastikan bahwa proyek menggunakan profil baru untuk penandatanganan kode. Untuk dokumentasi penyediaan perangkat Xamarin resmi, lihat Penyediaan Perangkat Xamarin.

  4. Klik ganda Info.plist untuk membukanya, lalu aktifkan RemoteNotifications di bawah Mode Latar Belakang.

Menambahkan notifikasi push ke aplikasi Anda

  1. Di QSTodoService, tambahkan properti berikut sehingga AppDelegate dapat memperoleh klien seluler:

    public MobileServiceClient GetClient {
        get
        {
            return client;
        }
        private set
        {
            client = value;
        }
    }
    
  2. Tambahkan pernyataan berikut using ke bagian atas file AppDelegate.cs .

    using Microsoft.WindowsAzure.MobileServices;
    using Newtonsoft.Json.Linq;
    
  3. Di AppDelegate, ganti acara FinishedLaunching :

     public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
     {
         // registers for push for iOS8
         var settings = UIUserNotificationSettings.GetSettingsForTypes(
             UIUserNotificationType.Alert
             | UIUserNotificationType.Badge
             | UIUserNotificationType.Sound,
             new NSSet());
    
         UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
         UIApplication.SharedApplication.RegisterForRemoteNotifications();
    
         return true;
     }
    
  4. Dalam file yang sama, ganti RegisteredForRemoteNotifications acara. Dalam kode ini Anda mendaftar untuk pemberitahuan template sederhana yang akan dikirim di semua platform yang didukung oleh server.

    Untuk informasi selengkapnya tentang templat dengan Hub Notifikasi, lihat Templat.

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        MobileServiceClient client = QSTodoService.DefaultService.GetClient;
    
        const string templateBodyAPNS = "{\"aps\":{\"alert\":\"$(messageParam)\"}}";
    
        JObject templates = new JObject();
        templates["genericMessage"] = new JObject
        {
            {"body", templateBodyAPNS}
        };
    
        // Register for push with your mobile app
        var push = client.GetPush();
        push.RegisterAsync(deviceToken, templates);
    }
    
  5. Kemudian, menimpa peristiwa DidReceivedRemoteNotification :

     public override void DidReceiveRemoteNotification (UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
     {
         NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
    
         string alert = string.Empty;
         if (aps.ContainsKey(new NSString("alert")))
             alert = (aps [new NSString("alert")] as NSString).ToString();
    
         //show alert
         if (!string.IsNullOrEmpty(alert))
         {
             UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null);
             avAlert.Show();
         }
     }
    

Aplikasi Anda sekarang diperbarui untuk mendukung pemberitahuan push.

Menguji notifikasi push di aplikasi Anda

  1. Tekan tombol Jalankan untuk membangun proyek dan memulai aplikasi di perangkat berkemampuan iOS, lalu klik OK untuk menerima pemberitahuan push.

    Catatan

    Anda harus secara eksplisit menerima pemberitahuan push dari aplikasi Anda. Permintaan ini hanya terjadi pertama kali aplikasi berjalan.

  2. Di aplikasi, ketik tugas, lalu klik ikon plus (+).

  3. Verifikasi bahwa pemberitahuan diterima, lalu klik OK untuk mengabaikan pemberitahuan.

  4. Ulangi langkah 2 dan segera tutup aplikasi, lalu verifikasi bahwa pemberitahuan ditampilkan.

Anda telah berhasil menyelesaikan tutorial ini.