Tutorial: 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 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 is used by Apple 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 launch pad.
  2. Click Keychain Access, expand Certificate Assistant, then click Request a Certificate from a Certificate Authority....

    Use Keychain Access to request a new certificate

  3. Select your User Email Address and Common Name, make sure that Saved to disk is selected, and then click Continue. Leave the CA Email Address field blank as it is not required.

    Required certificate information

  4. Type a name for the Certificate Signing Request (CSR) file in Save As, select the location in Where, then click Save.

    Choose a filename for the certificate

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

Next, you 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 be able to send push notifications to an iOS app, you must register your application with Apple and also register for push notifications.

  1. If you have not already registered your app, navigate to the iOS Provisioning Portal at the Apple Developer Center, sign in with your Apple ID, click Identifiers, then click App IDs, and finally click on the + sign to register a new app.

    iOS Provisioning Portal App IDs page

  2. Update the following three fields for your new app and then click Continue:

    • Name: Type a descriptive name for your app in the Name field in the App ID Description section.
    • Bundle Identifier: Under the Explicit App ID section, enter a Bundle Identifier in the form <Organization Identifier>.<Product Name> as mentioned in the App Distribution Guide. The Organization Identifier and Product Name you use must match the organization identifier and product name you use when you create your XCode project. In the following screenshot NotificationHubs is used as an organization identifier and GetStarted is used as the product name. Making sure this value matches the value you use in your XCode project allows you to use the correct publishing profile with XCode.
    • Push Notifications: Check the Push Notifications option in the App Services section.

      Form to register a new App ID

      This action generates your App ID and requests you to confirm the information. Click Register to confirm the new App ID.

      Once you click Register, you see the Registration complete screen, as shown in the following image. Click Done.

      App ID registration complete showing entitlements

  3. In the Developer Center, under App IDs, locate the app ID that you created, and click on its row.

    App ID list

    Clicking on the app ID displays the app details. Click the Edit button at the bottom.

    Edit App ID page

  4. Scroll to the bottom of the screen, and click the Create Certificate... button under the section Development Push SSL Certificate.

    Create certificate for App ID button

    You see the Add iOS Certificate assistant.

    Note

    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.

  5. Click Choose File, browse to the location where you saved the CSR file that you created in the first task, then click Generate.

    Generated certificate CSR upload page

  6. After the certificate is created by the portal, click the Download button, and click Done.

    Generated certificate download page

    It downloads the certificate and saves it to your computer in your Downloads folder.

    Locate certificate file in the Downloads folder

    Note

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

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

    The name in your certificate might be different, but it will be prefixed with Apple Development iOS Push Services.

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

    Export certificate as p12 format

    Make a note of the file name and location of the exported .p12 certificate. It is used to enable authentication with APNS.

    Note

    This tutorial creates a QuickStart.p12 file. Your file name and location might be different.

Create a provisioning profile for the app

  1. Back in the iOS Provisioning Portal, select Provisioning Profiles, select All, and then click the + (plus) button to create a new profile. You see the Add iOS Provisioning Profile wizard:

    Provisioning profile list

  2. Select iOS App Development under Development as the provisioning profile type, and click Continue.

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

    Select the App ID

  4. In the Select certificates screen, select your usual development certificate used for code signing, and click Continue. This certificate is not the push certificate you created.

    Select the certificate

  5. Next, select the Devices to use for testing, and click Continue

    Select the devices

  6. Finally, pick a name for the profile in Profile Name, click Generate.

    Choose a provisioning profile name

  7. When the new provisioning profile is created click to download it and install it on your Xcode development machine. Then click Done.

    Download the provisioning profile

Configure your notification hub for iOS push notifications

This section walks you through the steps to create a new notification hub and configure authentication with APNs using the .p12 push certificate that you previously created. If you want to use a notification hub that you have already created, you can skip to step 5.

  1. Sign in to the Azure portal.

  2. Select Create a resource > Mobile > Notification Hub.

    Azure portal - create a notification hub

  3. In the Notification Hub box, type a unique name. Select your Region, Subscription, and Resource Group (if you have one already).

    If you don't already have a service bus namespace, you can use the default name, which is created based on the hub name (if the namespace name is available).

    If you already have a service bus namespace that you want to create the hub in, follow these steps

    a. In the Namespace area, select the Select Existing link.

    b. Select Create.

    Azure portal - set notification hub properties

  4. Select Notifications (Bell icon), and select Go to resource.

    Azure portal - notifications -> Go to resource

  5. Select Access Policies from the list. Note the two connection strings that are available to you. You need them to handle push notifications later.

    Important

    Do NOT use the DefaultFullSharedAccessSignature in your application. This is meant to be used in your back-end only.

    Azure portal - notification hub connection strings

Configure iOS settings for the notification hub

  1. Select Apple (APNS) in the NOTIFICATION SETTINGS group.
  2. Select Certificate, click the file icon, and select the .p12 file that you exported earlier.
  3. Specify the password for the certificate.
  4. Select Sandbox mode. Use the Production mode only if you want to send push notifications to users who purchased your app from the store.

    Configure APNs in Azure portal

    Configure APNs certification in Azure portal

Your notification hub is now configured to work with APNs, and you 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 hit 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 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 your hub name 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;
    
  8. Declare an instance of SBNotificationHub:

    private SBNotificationHub Hub { get; set; }
    
  9. 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.Sound | 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. Override the RegisteredForRemoteNotifications() method in AppDelegate.cs:

    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. Override the ReceivedRemoteNotification() method in AppDelegate.cs:

    public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
    {
        ProcessNotification(userInfo, false);
    }
    
  12. Create the following ProcessNotification() method in AppDelegate.cs:

    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();
                }
            }
        }
    }
    

    Note

    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

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: