將推播通知新增至 Xamarin.iOS 應用程式

概觀

在本教學課程中,您會將推播通知新增至 Xamarin.iOS 快速入門專案,以便在每次插入一筆記錄時傳送推播通知至裝置。

如果您不要使用下載的快速入門伺服器專案,將需要推播通知擴充套件。 如需詳細資訊,請參閱使用 Azure Mobile Apps 的 .NET 後端伺服器 SDK

必要條件

在 Apple 的開發人員入口網站註冊應用程式以取得推播通知

設定您的行動應用程式以傳送推播通知

  1. 在您的 Mac 上啟動 Keychain Access。 在左側導覽列的 [類別] 下,開啟 [我的憑證]。 尋找您在上一節中下載的 SSL 憑證,然後公開其內容。 僅選取憑證 (不選取私密金鑰)。 然後將它匯出
  2. Azure 入口網站中,選取 [瀏覽全部]>[應用程式服務]。 然後選取您的 Mobile Apps 後端。
  3. 在 [設定] 下,選取 [App Service 推播]。 然後選取您的通知中樞名稱。
  4. 移至Apple Push Notification Services>Upload 憑證。 上傳 .p12 檔案,選取正確的模式 (根據您稍早的用戶端 SSL 憑證為生產或沙箱)。 儲存任何變更。

您的服務現在已設定成在 iOS 上使用推播通知。

更新伺服器專案以傳送推播通知

在本節中,您會更新現有 Mobile Apps 後端專案中的程式碼,以在每次新增項目時傳送推播通知。 此程序是由 Azure 通知中樞的範本功能所提供,可啟用跨平台推播。 各種用戶端會使用範本來註冊推播通知,而單一通用推播即可送達所有的用戶端平台。

選擇下列其中一個符合您後端專案類型的程式,也就是 .net 後 端或 Node.js 後端。

.NET 後端專案

  1. 在 Visual Studio 中,以滑鼠右鍵按一下伺服器專案。 然後選取 [管理 NuGet 套件] 。 搜尋 Microsoft.Azure.NotificationHubs,然後選取 [安裝]。 此程序會安裝通知中樞程式庫,以便從後端傳送通知。

  2. 在伺服器專案中,開啟 [控制器>TodoItemController]。 然後新增下列 using 陳述式:

    using System.Collections.Generic;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Azure.Mobile.Server.Config;
    
  3. PostTodoItem 方法中,於呼叫 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");
    }
    

    插入新的項目時,此程序會傳送包含 item.Text 的範本通知。

  4. 發佈伺服器專案。

Node.js 後端專案

  1. 設定您的後端專案。

  2. 在 todoitem.js 中,以下列程式碼取代現有的程式碼:

    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;  
    

    插入新的項目時,此程序會傳送包含 item.Text 的範本通知。

  3. 當您在本機電腦上編輯檔案時,請重新發佈伺服器專案。

設定您的 Xamarin.iOS 專案

在 Xamarin Studio 中設定 iOS 專案

  1. 在 Xamarin 中,開啟 plist,並以您稍早使用新的應用程式識別碼建立的套件組合識別碼更新套件組合 識別碼

  2. 向下捲動到 [背景模式]。 選取 [啟用背景模式] 方塊與 [遠端通知] 方塊。

  3. 按兩下 [方案面板] 中的專案,以開啟 [專案選項]

  4. 選擇 [建置] 下的 [iOS 套件組合簽署],然後選取對應的身分識別以及您為此專案設定的 [佈建設定檔]。

    這將確保專案使用新的設定檔進行程式碼簽署。 如需官方 Xamarin 裝置佈建文件,請參閱 Xamarin 裝置佈建

在 Visual Studio 中設定 iOS 專案

  1. 在 Visual Studio 中,以滑鼠右鍵按一下專案,然後按一下 [屬性]

  2. 在 [屬性] 頁面中,按一下 [iOS 應用程式] 索引標籤,然後使用您稍早建立的識別碼更新 [識別碼]

  3. 在 [iOS 套件組合簽署] 索引標籤中,選取對應的身分識別以及您為此專案設定的佈建設定檔。

    這將確保專案使用新的設定檔進行程式碼簽署。 如需官方 Xamarin 裝置佈建文件,請參閱 Xamarin 裝置佈建

  4. 按兩下 Info.plist 以開啟,並啟用 [背景模式] 下的 RemoteNotifications

將推播通知新增至應用程式

  1. QSTodoService 中新增下列屬性,以便讓 AppDelegate 能夠取得行動用戶端:

    public MobileServiceClient GetClient {
        get
        {
            return client;
        }
        private set
        {
            client = value;
        }
    }
    
  2. 將下列 using 陳述式加入至 AppDelegate.cs 檔案頂端。

    using Microsoft.WindowsAzure.MobileServices;
    using Newtonsoft.Json.Linq;
    
  3. AppDelegate 中,覆寫 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. 在相同檔案中,覆寫 RegisteredForRemoteNotifications 事件。 透過此程式碼,您將註冊能夠在伺服器所支援的所有平台間傳送的簡單範本通知。

    如需有關通知中樞範本的詳細資訊,請參閱 範本

    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. 然後,覆寫 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();
         }
     }
    

您的應用程式現在已更新為支援推播通知。

在應用程式中測試推播通知

  1. 按 [執行] 按鈕以建置專案並在可執行 iOS 的裝置上啟動應用程式,然後按一下 [確定] 以接受推播通知。

    注意

    您必須明確地接受來自應用程式的推播通知。 只有在應用程式第一次執行時,才會發生此要求。

  2. 在應用程式中,輸入工作,然後按一下加號 (+) 圖示。

  3. 確認已收到通知,然後按一下 [確定] 關閉通知。

  4. 重複執行步驟 2 並立即關閉應用程式,接著確認通知已顯示。

您已成功完成此教學課程。