教學課程:使用 Azure 通知中樞將推播通知傳送至 Xamarin.iOS 應用程式Tutorial: Send push notifications to Xamarin.iOS apps using Azure Notification Hubs

概觀Overview

本教學課程示範如何使用 Azure 通知中樞將推播通知傳送至 iOS 應用程式。This tutorial shows you how to use Azure Notification Hubs to send push notifications to an iOS application. 您會使用 Apple Push Notification Service (APNS) 建立可接收推播通知的空白 Xamarin.iOS 應用程式。You create a blank Xamarin.iOS app that receives push notifications by using the Apple Push Notification service (APNs).

完成之後,您將可使用通知中樞,將推播通知廣播到所有執行您的應用程式的裝置。When you're finished, you are able to use your notification hub to broadcast push notifications to all the devices running your app. NotificationHubs 應用程式範例中提供完成的程式碼。The finished code is available in the NotificationHubs app sample.

在本教學課程中,您會建立/更新程式碼以執行下列工作:In this tutorial, you create/update code to do the following tasks:

  • 產生憑證簽署要求檔案Generate the certificate signing request file
  • 針對推播通知註冊應用程式Register your app for push notifications
  • 建立應用程式的佈建設定檔Create a provisioning profile for the app
  • 針對 iOS 推播通知設定您的通知中樞Configure your notification hub for iOS push notifications
  • 傳送測試推播通知Send test push notifications

必要條件Prerequisites

  • Azure 訂用帳戶Azure subscription. 如果您沒有 Azure 訂用帳戶,請在開始前建立免費 Azure 帳戶If you don't have an Azure subscription, create a free Azure account before you begin.

  • 最新版的 XcodeLatest version of Xcode

  • iOS 10 (或更新版本) 相容的裝置An iOS 10 (or later version) compatible device

  • Apple Developer Program 成員資格。Apple Developer Program membership.

  • Visual Studio for MacVisual Studio for Mac

    注意

    基於 iOS 推播通知的組態需求,您必須在實體 iOS 裝置 (iPhone 或 iPad) 上部署和測試範例應用程式,而不是在模擬器中。Because of configuration requirements for iOS push notifications, you must deploy and test the sample application on a physical iOS device (iPhone or iPad) instead of in the simulator.

完成本教學課程是 Xamarin.iOS 應用程式的所有其他通知中樞教學課程的先決條件。Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for Xamarin.iOS apps.

產生憑證簽署要求檔案Generate the certificate-signing request file

Apple Push Notification Service (APNs) 使用憑證來驗證您的通知服務。The Apple Push Notification Service (APNs) uses certificates to authenticate your push notifications. 遵循下列指示來建立必要的推播憑證,以便傳送和接收通知。Follow these instructions to create the necessary push certificate to send and receive notifications. 如需這些概念的詳細資訊,請參閱 Apple Push Notification Service 官方文件。For more information on these concepts, see the official Apple Push Notification Service documentation.

產生憑證簽署要求 (CSR) 檔案,Apple 會用此檔案來產生簽署的推播憑證。Generate the Certificate Signing Request (CSR) file, which Apple uses to generate a signed push certificate.

  1. 在您的 Mac 上,執行「鑰匙圈存取」工具。On your Mac, run the Keychain Access tool. 此工具可從啟動控制板上的 [公用程式] 資料夾或 [其他] 資料夾開啟。It can be opened from the Utilities folder or the Other folder on the Launchpad.

  2. 選取 [金鑰鏈存取] ,並展開 [憑證助理] ,然後選取 [從憑證授權單位要求憑證] 。Select Keychain Access, expand Certificate Assistant, and then select Request a Certificate from a Certificate Authority.

    使用金鑰鏈存取要求新憑證

  3. 選取您的使用者電子郵件地址,輸入一般名稱值,並確定您已指定 [儲存至磁碟] ,然後選取 [繼續] 。Select your User Email Address, enter your Common Name value, make sure that you specify Saved to disk, and then select Continue. 請將 [CA 電子郵件地址] 留空,因為這不是必要資訊。Leave CA Email Address blank as it isn't required.

    必要的憑證資訊

  4. 在 [另存新檔] 中輸入 CSR 檔案的名稱,在 [位置] 中選取位置,然後選取 [儲存] 。Enter a name for the CSR file in Save As, select the location in Where, and then select Save.

    選擇憑證的檔案名稱

    此動作會在選取的位置儲存 CSR 檔案。This action saves the CSR file in the selected location. 預設位置是桌面The default location is Desktop. 請記住為檔案選擇的位置。Remember the location chosen for the file.

接著,向 Apple 註冊您的應用程式,並啟用推播通知,然後上傳這個匯出的 CSR 建立推播憑證。Next, register your app with Apple, enable push notifications, and upload the exported CSR to create a push certificate.

針對推播通知註冊應用程式Register your app for push notifications

若要將推播通知傳送至 iOS 應用程式,請向 Apple 註冊您的應用程式,並註冊進行推播通知。To send push notifications to an iOS app, register your application with Apple, and also register for push notifications.

  1. 如果您尚未註冊應用程式,請瀏覽至 Apple Developer Center 上的 iOS 佈建入口網站If you haven't already registered your app, browse to the iOS Provisioning Portal at the Apple Developer Center. 使用您的 Apple ID 登入入口網站,然後選取 [識別碼] 。Sign in to the portal with your Apple ID, and select Identifiers. 然後選取 [+] 以註冊新的應用程式。Then select + to register a new app.

    iOS 佈建入口網站應用程式識別碼頁面

  2. 在 [註冊新識別碼] 畫面上,選取 [應用程式識別碼] 選項按鈕。On the Register a New Identifier screen, select the App IDs radio button. 然後選取 [繼續] 。Then select Continue.

    iOS 佈建入口網站的 [註冊新識別碼] 頁面

  3. 將新應用程式的下列三個值予以更新,然後選取 [繼續] :Update the following three values for your new app, and then select Continue:

    • 描述:輸入您應用程式的描述性名稱。Description: Type a descriptive name for your app.

    • 套件組合識別碼:以應用程式分發指南 (英文) 中所提的 Organization Identifier.Product Name 形式輸入套件組合識別碼。Bundle ID: Enter a Bundle ID of the form Organization Identifier.Product Name as mentioned in the App Distribution Guide. [組織識別碼] 和 [產品名稱] 值必須符合當您建立 Xcode 專案時使用的組織識別碼和產品名稱。The Organization Identifier and Product Name values must match the organization identifier and product name you use when you create your Xcode project. 在下列螢幕擷取畫面中,NotificationHubs 值會作為組織識別碼,GetStarted 值會作為產品名稱。In the following screenshot, the NotificationHubs value is used as an organization identifier and the GetStarted value is used as the product name. 請確定套件組合識別碼值符合您 Xcode 專案中的值,好讓 Xcode 使用正確的發行設定檔。Make sure the Bundle Identifier value matches the value in your Xcode project, so that Xcode uses the correct publishing profile.

      iOS 佈建入口網站的 [註冊應用程式識別碼] 頁面

    • 推播通知:勾選 [功能] 區段中的 [推播通知] 選項。Push Notifications: Check the Push Notifications option in the Capabilities section.

      註冊新應用程式識別碼的表單

      此動作會產生您的應用程式識別碼,並要求您確定此資訊。This action generates your App ID and requests that you confirm the information. 選取 [繼續] ,然後選取 [註冊] 以確認新的應用程式識別碼。Select Continue, then select Register to confirm the new App ID.

      確認新的應用程式識別碼

      選取註冊之後,您會在 [憑證、識別碼與設定檔] 頁面中看到作為明細項目的新應用程式識別碼。After you select Register, you see the new App ID as a line item in the Certificates, Identifiers & Profiles page.

  4. 在 [憑證、識別碼與設定檔] 頁面的 [識別碼] 底下,找出您剛才建立的應用程式識別碼明細項目,然後選取其資料列以顯示 [編輯您的應用程式識別碼設定] 畫面。In the Certificates, Identifiers & Profiles page, under Identifiers, locate the App ID line item that you just created, and select its row to display the Edit your App ID Configuration screen.

  5. 向下瀏覽至已核取的 [推播通知] 選項,然後選取 [設定] 來建立憑證。Scroll down to the checked Push Notifications option, and then select Configure to create the certificate.

    編輯應用程式識別碼頁面

  6. [Apple 推播通知服務 SSL 憑證] 視窗隨即出現。The Apple Push Notification service SSL Certificates window appears. 在 [開發 SSL 憑證] 區段下方,選取 [建立憑證] 按鈕。Select the Create Certificate button under the Development SSL Certificate section.

    為應用程式識別碼建立憑證的按鈕

    [建立新憑證] 畫面會隨即顯示。The Create a new Certificate screen is displayed.

    注意

    本教學課程使用開發憑證。This tutorial uses a development certificate. 註冊生產憑證時,將使用同一個程序。The same process is used when registering a production certificate. 只要確定在傳送通知時使用相同的憑證類型即可。Just make sure that you use the same certificate type when sending notifications.

  7. 選取 [選擇檔案] ,瀏覽到您在第一個工作中儲存 CSR 檔案的位置,然後按兩下憑證名稱來將其下載。Select Choose File, browse to the location where you saved the CSR file from the first task, and then double-click the certificate name to load it. 然後選取 [繼續] 。Then select Continue.

  8. 在入口網站建立憑證之後,請選取 [下載] 按鈕。After the portal creates the certificate, select the Download button. 儲存憑證,並記住其儲存位置。Save the certificate, and remember the location to which it's saved.

    產生的憑證 CSR 下載頁面

    這會下載憑證並將其儲存到您電腦中的 [下載] 資料夾。The certificate is downloaded and saved to your computer in your Downloads folder.

    在 [下載] 資料夾中找出憑證檔案

    注意

    依預設,下載的開發憑證會名為 aps_development.cerBy default, the downloaded development certificate is named aps_development.cer.

  9. 按兩下下載的推播憑證 aps_development.cerDouble-click the downloaded push certificate aps_development.cer. 此動作會將新的憑證安裝在金鑰鏈中,如下圖所示:This action installs the new certificate in the Keychain, as shown in the following image:

    顯示新憑證的金鑰鏈存取憑證清單

    注意

    雖然憑證中的名稱可能會不同,不過名稱會加上 Apple Development iOS Push Services 前置詞。Although the name in your certificate might be different, the name will be prefixed with Apple Development iOS Push Services.

  10. 在 Keychain Access 中,以滑鼠右鍵按一下您在 [憑證] 類別中建立的新推播憑證。In Keychain Access, right-click the new push certificate that you created in the Certificates category. 選取 [匯出] 、為檔案命名、選取 [.p12] 格式,然後選取 [儲存] 。Select Export, name the file, select the .p12 format, and then select Save.

    以 p12 格式匯出憑證

    您可以選擇使用密碼來保護憑證,但這是選擇性的。You can choose to protect the certificate with a password, but this is optional. 如果您想要略過密碼建立,請按一下 [確定] 。Click OK if you want to bypass password creation. 記下匯出的 .p12 憑證的檔案名稱和位置。Make a note of the file name and location of the exported .p12 certificate. 其可用來啟用 APNs 驗證功能。They are used to enable authentication with APNs.

    注意

    您的 .p12 檔案名稱和位置可能與本教學課程中所顯示的不同。Your .p12 file name and location might be different than what is pictured in this tutorial.

建立應用程式的佈建設定檔Create a provisioning profile for the app

  1. 返回 iOS 佈建入口網站,選取 [憑證、識別碼與設定檔] ,從左側功能表中選取 [設定檔] ,然後選取 [+] 以建立新的設定檔。Return to the iOS Provisioning Portal, select Certificates, Identifiers & Profiles, select Profiles from the left menu, and then select + to create a new profile. [註冊新佈建設定檔] 的畫面會隨即出現。The Register a New Provisioning Profile screen appears.

  2. 在 [開發] 下,選取 [iOS 應用程式開發] 作為佈建設定檔類型,然後選取 [繼續] 。Select iOS App Development under Development as the provisioning profile type, and then select Continue.

    佈建設定檔清單

  3. 接著,從 [應用程式識別碼] 下拉式清單選取您建立的應用程式識別碼,然後選取 [繼續] 。Next, select the app ID you created from the App ID drop-down list, and select Continue.

    選取應用程式識別碼

  4. 在 [選取憑證] 視窗中,選取用於程式碼簽署的開發憑證,然後選取 [繼續] 。In the Select certificates window, select the development certificate that you use for code signing, and select Continue. 此憑證不是您建立的推播憑證。This certificate isn't the push certificate you created. 如果沒有憑證存在,您必須加以建立。If one does not exist, you must create it. 如果憑證存在,請跳到下一個步驟。If a certificate does exist, skip to the next step. 若要建立開發憑證 (憑證不存在的話):To create a development certificate if one does not exist:

    1. 如果您看到 [沒有可用憑證] ,請選取 [建立憑證] 。If you see No Certificates are available, select Create Certificate.
    2. 在 [軟體] 區段中,選取 [Apple 開發] 。In the Software section, select Apple Development. 然後選取 [繼續] 。Then select Continue.
    3. 在 [建立新憑證] 畫面中,選取 [選擇檔案] 。In the Create a New Certificate screen, select Choose File.
    4. 瀏覽至您稍早建立的憑證簽署要求憑證並加以選取,然後選取 [開啟] 。Browse to the Certificate Signing Request certificate you created earlier, select it, and then select Open.
    5. 選取 [繼續] 。Select Continue.
    6. 下載開發憑證,並記住其儲存位置。Download the development certificate, and remember the location to which it's saved.
  5. 返回 [憑證、識別碼與設定檔] 頁面,從左側功能表中選取 [設定檔] ,然後選取 [+] 以建立新的設定檔。Return to the Certificates, Identifiers & Profiles page, select Profiles from the left menu, and then select + to create a new profile. [註冊新佈建設定檔] 的畫面會隨即出現。The Register a New Provisioning Profile screen appears.

  6. 在 [選取憑證] 視窗中,選取您剛才建立的開發憑證。In the Select certificates window, select the development certificate that you just created. 然後選取 [繼續] 。Then select Continue.

  7. 接下來,選取要用來測試的裝置,然後選取 [繼續] 。Next, select the devices to use for testing, and select Continue.

  8. 最後,在 [佈建設定檔名稱] 中為設定檔選擇名稱,然後選取 [產生] 。Finally, choose a name for the profile in Provisioning Profile Name, and select Generate.

    選擇佈建設定檔名稱

  9. 建立新的佈建設定檔後,請選取 [下載] 。When the new provisioning profile is created, select Download. 記住其儲存位置。Remember the location to which it's saved.

  10. 瀏覽至佈建設定檔的位置,然後按兩下來將其安裝在您的 Xcode 開發機器上。Browse to the location of the provisioning profile, and then double-click it to install it on your Xcode development machine.

建立通知中樞Create a notification hub

在本節中,您會建立通知中樞,並使用您先前建立的 .p12 推播憑證,設定以 APNs 進行驗證的機制。In this section, you create a notification hub and configure authentication with APNs by using the .p12 push certificate that you previously created. 如果您想要使用已經建立的通知中樞,可以跳至步驟 5。If you want to use a notification hub that you've already created, you can skip to step 5.

  1. 登入 Azure 入口網站Sign in to the Azure portal.

  2. 選取左功能表上的 [所有服務] ,然後選取 [行動] 區段中的 [通知中樞] 。Select All services on the left menu, and then select Notification Hubs in the Mobile section. 選取服務名稱旁邊的星號圖示,將服務加到左功能表上的 [我的最愛] 區段。Select the star icon next to the service name to add the service to the FAVORITES section on the left menu. 在 [通知中樞] 加到 [我的最愛] 之後,在左功能表上予以選取。After you add Notification Hubs to FAVORITES, select it on the left menu.

    Azure 入口網站 - 選取通知中樞

  3. 在 [通知中樞] 頁面上,選取工具列上的 [新增] 。On the Notification Hubs page, select Add on the toolbar.

    通知中樞 - 新增工具列按鈕

  4. 在 [通知中樞] 頁面上,執行下列步驟:On the Notification Hub page, do the following steps:

    1. 在 [通知中樞] 中輸入名稱。Enter a name in Notification Hub.

    2. 在 [建立新的命名空間] 中輸入名稱。Enter a name in Create a new namespace. 命名空間包含一或多個中樞。A namespace contains one or more hubs.

    3. 從 [位置] 下拉式清單方塊選取值。Select a value from the Location drop-down list box. 此值會指定您要在其中建立中樞的位置。This value specifies the location in which you want to create the hub.

    4. 在 [資源群組] 中選取現有的資源群組,或建立一個新群組。Select an existing resource group in Resource Group, or create a name for a new resource group.

    5. 選取 [建立] 。Select Create.

      Azure 入口網站 - 設定通知中樞屬性

  5. 選取 [通知] (鈴鐺圖示),然後選取 [前往資源] 。Select Notifications (the bell icon), and then select Go to resource. 您也可以重新整理 [通知中樞] 頁面中的清單,然後選取您的中樞。You can also refresh the list on the Notification Hubs page and select your hub.

    Azure 入口網站 - 通知 -> 前往資源

  6. 從清單中選取 [存取原則] 。Select Access Policies from the list. 請記下您可使用的兩個連接字串。Note that the two connection strings are available to you. 您稍後需要用到這些連接字串來處理推播通知。You'll need them later to handle push notifications.

    重要

    「請勿」 在應用程式中使用 DefaultFullSharedAccessSignature 原則。Do not use the DefaultFullSharedAccessSignature policy in your application. 這只能在後端使用。This is meant to be used in your back end only.

    Azure 入口網站 - 通知中樞連接字串

使用 APNs 資訊設定您的通知中樞Configure your notification hub with APNs information

  1. 在 [Notification Services] 下,選取 [Apple (APNS)] 。Under Notification Services, select Apple (APNS).

  2. 選取 [憑證] 。Select Certificate.

  3. 選取 [檔案] 圖示。Select the file icon.

  4. 選取您先前匯出的 .p12 檔案,然後選取 [開啟] 。Select the .p12 file that you exported earlier, and then select Open.

  5. 若有需要,請指定正確的密碼。If required, specify the correct password.

  6. 選取 [沙箱] 模式。Select Sandbox mode. 只有在您想傳送推播通知給從市集購買應用程式的使用者時,才可使用 [生產] 模式。Use the Production mode only if you want to send push notifications to users who purchased your app from the store.

    在 Azure 入口網站中設定 APNS 憑證

  7. 選取 [儲存] 。Select Save.

您現在已使用 APNs 來設定通知中樞。You've now configured your notification hub with APNs. 您也擁有可用來註冊應用程式和傳送推播通知的連接字串。You also have the connection strings to register your app and send push notifications.

將您的應用程式連接到通知中樞Connect your app to the notification hub

建立新專案Create a new project

  1. 在 Visual Studio 中建立新的 iOS 專案,並選取 [單一檢視應用程式] 範本,然後按 [下一步] In Visual Studio, create a new iOS project and select the Single View App template, and click Next

    Visual Studio - 選取應用程式類型

  2. 輸入應用程式名稱和組織識別碼,然後按 [下一步] 和 [建立] 。Enter your App Name and Organization identifier, then click Next, then Create

  3. 在 [方案] 檢視中,按兩下 Into.plist,並確定 [身分識別] 下方的套件組合識別碼符合您在建立佈建設定檔時所使用的套件組合識別碼。From the Solution view, double-click Info.plist and under Identity make sure your Bundle Identifier matches the one used when creating your provisioning profile. 在 [簽署] 下方,確定您已於 [小組] 下方選取您的開發人員帳戶,已選取 [自動管理簽署],並已自動選取您的簽署憑證和佈建設定檔。Under Signing ensure that your Developer account is selected under Team, "Automatically manage signing" is selected and your Signing Certificate and Provisioning Profile are automatically selected.

    Visual Studio- iOS 應用程式組態

  4. 在 [解決方案] 檢視中按兩下 Entitlements.plist,並確定已核取 [啟用推播通知] 。From the Solution view, double-click the Entitlements.plist and ensure that Enable Push Notifications is checked.

    Visual Studio- iOS 權利組態

  5. 新增 Azure 傳訊套件。Add the Azure Messaging package. 在 [方案] 檢視中,以滑鼠右鍵按一下專案,然後選取 [新增] > [新增 NuGet 套件] 。In the Solution view, right-click the project and select Add > Add NuGet Packages. 搜尋 Xamarin.Azure.NotificationHubs.iOS,並將此套件新增至專案中。Search for Xamarin.Azure.NotificationHubs.iOS and add the package to your project.

  6. 在您的類別中新增檔案,將其命名為 Constants.cs,然後新增下列變數並以 先前記下的 hubnameDefaultListenSharedAccessSignature 取代字串常值預留位置。Add a new file to your class, name it Constants.cs and add the following variables and replace the string literal placeholders with the hubname and the DefaultListenSharedAccessSignature noted earlier.

    // Azure app-specific connection string and hub path
    public const string ListenConnectionString = "<Azure DefaultListenSharedAccess Connection String>";
    public const string NotificationHubName = "<Azure Notification Hub Name>";
    
  7. AppDelegate.cs 中新增下列 using 陳述式:In AppDelegate.cs, add the following using statement:

    using WindowsAzure.Messaging;
    using UserNotifications
    
  8. 宣告 SBNotificationHub 的執行個體:Declare an instance of SBNotificationHub:

    private SBNotificationHub Hub { get; set; }
    
  9. AppDelegate.cs 中,更新 FinishedLaunching() 以符合下列程式碼:In AppDelegate.cs, update FinishedLaunching() to match the following code:

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
                                                                    (granted, error) =>
            {
                if (granted)
                    InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
            });
        } else if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
            var pushSettings = UIUserNotificationSettings.GetSettingsForTypes (
                    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
                    new NSSet ());
    
            UIApplication.SharedApplication.RegisterUserNotificationSettings (pushSettings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications ();
        } else {
            UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
            UIApplication.SharedApplication.RegisterForRemoteNotificationTypes (notificationTypes);
        }
    
        return true;
    }
    
  10. AppDelegate.cs 中覆寫 RegisteredForRemoteNotifications() 方法:In AppDelegate.cs, override the RegisteredForRemoteNotifications() method:

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);
    
        Hub.UnregisterAllAsync (deviceToken, (error) => {
            if (error != null)
            {
                System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
                return;
            }
    
            NSSet tags = null; // create tags if you want
            Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
                if (errorCallback != null)
                    System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
            });
        });
    }
    
  11. AppDelegate.cs 中覆寫 ReceivedRemoteNotification() 方法:In AppDelegate.cs, override the ReceivedRemoteNotification() method:

    public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
    {
        ProcessNotification(userInfo, false);
    }
    
  12. AppDelegate.cs 中建立 ProcessNotification() 方法:In AppDelegate.cs, create the ProcessNotification() method:

    void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
    {
        // Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
        if (null != options && options.ContainsKey(new NSString("aps")))
        {
            //Get the aps dictionary
            NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;
    
            string alert = string.Empty;
    
            //Extract the alert text
            // NOTE: If you're using the simple alert by just specifying
            // "  aps:{alert:"alert msg here"}  ", this will work fine.
            // But if you're using a complex alert with Localization keys, etc.,
            // your "alert" object from the aps dictionary will be another NSDictionary.
            // Basically the JSON gets dumped right into a NSDictionary,
            // so keep that in mind.
            if (aps.ContainsKey(new NSString("alert")))
                alert = (aps [new NSString("alert")] as NSString).ToString();
    
            //If this came from the ReceivedRemoteNotification while the app was running,
            // we of course need to manually process things like the sound, badge, and alert.
            if (!fromFinishedLaunching)
            {
                //Manually show an alert
                if (!string.IsNullOrEmpty(alert))
                {
                    UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null);
                    avAlert.Show();
                }
            }
        }
    }
    

    注意

    您可以選擇覆寫 FailedToRegisterForRemoteNotifications() 以處理沒有網路連線等的情況。You can choose to override FailedToRegisterForRemoteNotifications() to handle situations such as no network connection. 這點特別重要,因為使用者可能在離線模式下 (例如飛機) 啟動您的應用程式,而您希望針對您的應用程式來處理推播傳訊案例。This is especially important where the user might start your application in offline mode (for example, Airplane) and you want to handle push messaging scenarios specific to your app.

  13. 在您的裝置上執行應用程式。Run the app on your device.

傳送測試推播通知Send test push notifications

您可以在 Azure 入口網站 中,使用 [測試傳送] 選項測試應用程式能否接收通知。You can test receiving notifications in your app with the Test Send option in the Azure portal. 它會將測試推播通知傳送至您的裝置。It sends a test push notification to your device.

Azure 入口網站 - 測試傳送

推播通知通常會以後端服務傳送,例如 Mobile Apps 或使用相容程式庫的 ASP.NET。Push notifications are normally sent in a back-end service like Mobile Apps or ASP.NET using a compatible library. 如果您的後端無法使用程式庫,您也可以直接使用 REST API 來傳送通知訊息。If a library is not available for your back-end, you can also use the REST API directly to send notification messages.

後續步驟Next steps

在本教學課程中,您已將廣播通知傳送至所有向後端註冊的 iOS 裝置。In this tutorial, you sent broadcast notifications to all your iOS devices registered with the backend. 若要了解如何將通知推送至特定 iOS 裝置,請繼續進行下列教學課程:To learn how to push notifications to specific iOS devices, advance to the following tutorial: