Tutorial: Send push notifications to Xamarin.iOS apps using Azure Notification Hubs

Overview

This tutorial shows you how to use Azure Notification Hubs to send push notifications to an iOS application. 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. 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
  • Configure your notification hub for iOS push notifications
  • Send test push notifications

Prerequisites

  • Azure subscription. If you don't have an Azure subscription, create a free Azure account before you begin.

  • Latest version of Xcode

  • An iOS 10 (or later version) compatible device

  • Apple Developer Program membership.

  • Visual Studio for Mac

    Note

    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.

Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for Xamarin.iOS apps.

Generate the certificate-signing request file

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. For more information on these concepts, see the official Apple Push Notification Service documentation.

Generate the Certificate Signing Request (CSR) file, which Apple uses to generate a signed push certificate.

  1. 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.

    Use Keychain Access to request a new certificate

    Note

    By default, Keychain Access selects the first item in the list. This can be a problem if you're in the Certificates category and Apple Worldwide Developer Relations Certification Authority is not the first item in the list. Make sure you have a non-key item, or the Apple Worldwide Developer Relations Certification Authority key is selected, before generating the CSR (Certificate Signing Request).

  3. Select your User Email Address, enter your Common Name value, make sure that you specify Saved to disk, and then select Continue. Leave CA Email Address blank as it isn't required.

    Required certificate information

  4. Enter a name for the CSR file in Save As, select the location in Where, and then select Save.

    Choose a file name for the certificate

    This action saves the CSR file in the selected location. The default location is Desktop. Remember the location chosen for the file.

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

To send push notifications to an iOS app, register your application with Apple, and also register for push notifications.

  1. If you haven't already registered your app, browse to the iOS Provisioning Portal at the Apple Developer Center. Sign in to the portal with your Apple ID, and select Identifiers. Then select + to register a new app.

    iOS Provisioning Portal App IDs page

  2. On the Register a New Identifier screen, select the App IDs radio button. Then select Continue.

    iOS Provisioning Portal register new ID page

  3. Update the following three values for your new app, and then select Continue:

    • Description: Type a descriptive name for your app.

    • Bundle ID: Enter a Bundle ID of the form Organization Identifier.Product Name as mentioned in the App Distribution Guide. The Organization Identifier and Product Name values must match the organization identifier and product name you use when you create your Xcode project. In the following screenshot, the NotificationHubs value is used as an organization identifier and the GetStarted value is used as the product name. Make sure the Bundle Identifier value matches the value in your Xcode project, so that Xcode uses the correct publishing profile.

      iOS Provisioning Portal register app ID page

    • Push Notifications: Check the Push Notifications option in the Capabilities section.

      Form to register a new App ID

      This action generates your App ID and requests that you confirm the information. Select Continue, then select Register to confirm the new App ID.

      Confirm 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.

Creating a Certificate for Notification Hubs

A certificate is required to enable the notification hub to work with APNS. This can be done in one of two ways:

  1. Create a .p12 that can be uploaded directly to Notification Hub.
  2. Create a .p8 that can be used for token-based authentication (the newer approach).

The newer approach has a number of benefits (compared to using certificates) as documented in Token-based (HTTP/2) authentication for APNS. However, steps have been provided for both approaches.

OPTION 1: Creating a .p12 push certificate that can be uploaded directly to Notification Hub

  1. Scroll down to the checked Push Notifications option, and then select Configure to create the certificate.

    Edit App ID page

  2. The Apple Push Notification service SSL Certificates window appears. Select the Create Certificate button under the Development SSL Certificate section.

    Create certificate for App ID button

    The Create a new Certificate screen is displayed.

    Note

    This tutorial uses a development certificate, which your app uses to generate a unique device token. The same process is used when registering a production certificate. Just make sure that you use the same certificate type when sending notifications.

  3. 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.

  4. After the portal creates the certificate, select the Download button. Save the certificate, and remember the location to which it's saved.

    Generated certificate download page

    The certificate is downloaded and saved to your computer in your Downloads folder.

    Locate certificate file in the Downloads folder

    Note

    By default, the downloaded development certificate is named aps_development.cer.

  5. Double-click the downloaded push certificate aps_development.cer. This action installs the new certificate in the Keychain, as shown in the following image:

    Keychain access certificates list showing new certificate

    Note

    Although the name in your certificate might be different, the name will be prefixed with Apple Development iOS Push Services.

  6. In Keychain Access, right-click the new push certificate that you created in the Certificates category. Select Export, name the file, select the .p12 format, and then select Save.

    Export certificate as p12 format

    You can choose to protect the certificate with a password, but this is optional. Click OK if you want to bypass password creation. Make a note of the file name and location of the exported .p12 certificate. They are used to enable authentication with APNs.

    Note

    Your .p12 file name and location might be different than what is pictured in this tutorial.

OPTION 2: Creating a .p8 certificate that can be used for token-based authentication

  1. Make note of the following details:

    • App ID Prefix (this is a Team ID)
    • Bundle ID
  2. Back in Certificates, Identifiers & Profiles, click Keys.

    Note

    If you already have a key configured for APNS, you can re-use the .p8 certificate that you downloaded right after it was created. If so, you can ignore steps 3 through 5.

  3. Click the + button (or the Create a key button) to create a new key.

  4. Provide a suitable Key Name value, then check the Apple Push Notifications service (APNs) option, and then click Continue, followed by Register on the next screen.

  5. Click Download and then move the .p8 file (prefixed with AuthKey_) to a secure local directory, then click Done.

    Note

    Be sure to keep your .p8 file in a secure place (and save a backup). After downloading your key, it cannot be re-downloaded as the server copy is removed.

  6. On Keys, click on the key that you just created (or an existing key if you have chosen to use that instead).

  7. Make note of the Key ID value.

  8. Open your .p8 certificate in a suitable application of your choice such as Visual Studio Code then make note of the key value. This is the value between -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- .

    -----BEGIN PRIVATE KEY-----
    <key_value>
    -----END PRIVATE KEY-----
    

    Note

    This is the token value that will be used later to configure Notification Hub.

At the end of these steps you should have the following information for use later in Configure your notification hub with APNs information:

  • Team ID (see step 1)
  • Bundle ID (see step 1)
  • Key ID (see step 7)
  • Token value i.e. the .p8 key value (see step 8)

Create a provisioning profile for the app

  1. 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. Select iOS App Development under Development as the provisioning profile type, and then select Continue.

    Provisioning profile list

  3. Next, select the app ID you created from the App ID drop-down list, and select Continue.

    Select the App ID

  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. 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.

    Choose a provisioning profile name

  9. When the new provisioning profile is created, select Download. Remember the location to which it's saved.

  10. 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

In this section, you create a notification hub and configure authentication with APNs by using either the .p12 push certificate or token-based authentication. If you want to use a notification hub that you've already created, you can skip to step 5.

  1. Sign in to the Azure portal.

  2. Select All services on the left menu. A screenshot showing select All Services for an existing namespace.

  3. Type Notification Hubs in the Filter services text box. Select the star icon next to the service name to add the service to the FAVORITES section on the left menu. Select Notification Hubs.

    A screenshot showing how to filter for notification hubs.

  4. On the Notification Hubs page, select Create on the toolbar.

    A screenshot showing how to create a new notification hub.

  5. In the Basics tab on the Notification Hub page, do the following steps:

    1. In Subscription, select the name of the Azure subscription you want to use, and then select an existing resource group, or create a new one.

    2. Enter a unique name for the new namespace in Namespace Details.

    3. A namespace contains one or more notification hubs, so type a name for the hub in Notification Hub Details.

    4. Select a value from the Location drop-down list box. This value specifies the location in which you want to create the hub.

      Screenshot showing notification hub details.

    5. Review the Availability Zones option. If you chose a region that has availability zones, the check box is selected by default. Availability Zones is a paid feature, so an additional fee is added to your tier.

    6. Choose a Disaster recovery option: None, Paired recovery region, or Flexible recovery region. If you choose Paired recovery region, the failover region is displayed. If you select Flexible recovery region, use the drop-down to choose from a list of recovery regions.

      Screenshot showing availability zone details.

    7. Select Create.

  6. When the deployment is complete select Go to resource.

Configure your notification hub with APNs information

Under Notification Services, select Apple (APNS) then follow the appropriate steps based on the approach you chose previously in the Creating a Certificate for Notification Hubs section.

Note

If you build your app with App Store or Ad-Hoc distribution profile, use the Production for Application Mode. This will allow your device to send push notifications to users who purchased your app from the store.

OPTION 1: Using a .p12 push certificate

  1. Select Certificate.

  2. Select the file icon.

  3. Select the .p12 file that you exported earlier, and then select Open.

  4. If required, specify the correct password.

  5. Select Sandbox mode.

    Configure APNs certification in Azure portal

  6. Select Save.

OPTION 2: Using token-based authentication

  1. Select Token.

  2. Enter the following values that you acquired earlier:

    • Key ID
    • Bundle ID
    • Team ID
    • Token
  3. Choose Sandbox

  4. Select Save.

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. In Visual Studio, create a new iOS project and select the Single View App template, and click Next

    Visual Studio - Select Application Type

  2. Enter your App Name and Organization identifier, then click Next, then Create

  3. 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 App Config

  4. From the Solution view, double-click the Entitlements.plist and ensure that Enable Push Notifications is checked.

    Visual Studio- iOS Entitlements Config

  5. Add the Azure Messaging package. In the Solution view, right-click the project and select Add > Add NuGet Packages. Search for Xamarin.Azure.NotificationHubs.iOS and add the package to your project.

  6. 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. In AppDelegate.cs, add the following using statement:

    using WindowsAzure.Messaging.NotificationHubs;
    using UserNotifications
    
  8. Create an implementation of the MSNotificationHubDelegate in the AppDelegate.cs:

    public class AzureNotificationHubListener : MSNotificationHubDelegate
    {
        public override void DidReceivePushNotification(MSNotificationHub notificationHub, MSNotificationHubMessage message)
        {
    
        }
    }
    
  9. In AppDelegate.cs, update FinishedLaunching() to match the following code:

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        // Set the Message listener
        MSNotificationHub.SetDelegate(new AzureNotificationHubListener());
    
        // Start the SDK
        MSNotificationHub.Start(ListenConnectionString, NotificationHubName);
    
        return true;
    }
    
  10. In AppDelegate.cs, implement the DidReceivePushNotification method for the AzureNotificationHubListener class:

    public override void DidReceivePushNotification(MSNotificationHub notificationHub, MSNotificationHubMessage message)
    {
        // This sample assumes { aps: { alert: { title: "Hello", body: "World" } } }
        var alertTitle = message.Title ?? "Notification";
        var alertBody = message.Body;
    
        var myAlert = UIAlertController.Create(alertTitle, alertBody, UIAlertControllerStyle.Alert);
        myAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
        UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(myAlert, true, null);
    }
    
  11. Run the app on your device.

Send test push notifications

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 portal - Test Send

Push notifications are normally sent in a back-end service like Mobile Apps or ASP.NET using a compatible library. If a library is not available for your back-end, you can also use the REST API directly to send notification messages.

Next steps

In this tutorial, you sent broadcast notifications to all your iOS devices registered with the backend. To learn how to push notifications to specific iOS devices, advance to the following tutorial: