iOS Push Notifications with Notification Hubs for Xamarin apps

Overview

Important

To complete this tutorial, you must have an active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see Azure Free Trial.

This tutorial shows you how to use Azure Notification Hubs to send push notifications to an iOS application. You'll create a blank Xamarin.iOS app that receives push notifications by using the Apple Push Notification Service (APNs). When you're finished, you'll be 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.

This tutorial demonstrates the simple push message broadcast scenario with Notification Hubs.

Prerequisites

This tutorial requires the following:

  • Xcode 6.0
  • An iOS 7.0 (or later version) compatible device
  • iOS Developer Program membership
  • Xamarin Studio

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

  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.

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

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

Next, you will register your app with Apple, enable push notifications, and upload this 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, log on with your Apple ID, click Identifiers, then click App IDs, and finally click on the + sign to register a new app.

  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 will use when you create your XCode project. In the screeshot below NotificationHubs is used as a organization idenitifier and GetStarted is used as the product name. Making sure this matches the values you will use in your XCode project will allow you to use the correct publishing profile with XCode.
    • Push Notifications: Check the Push Notifications option in the App Services section, .

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

      Once you click Register, you will see the Registration complete screen, as shown below. Click Done.

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

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

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

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

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

    This downloads the certificate and saves it to your computer in your 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 installs the new certificate in the Keychain, as shown below:

    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.

    Make a note of the file name and location of the exported .p12 certificate. It will be 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 + button to create a new profile. This launches the Add iOS Provisiong Profile Wizard

  2. Select iOS App Development under Development as the provisiong profile type, and click Continue.
  3. Next, select the app ID you just created from the App ID drop-down list, and click Continue

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

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

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

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

Configure your notification hub

This section walks you through creating a new notification hub and configuring authentication with APNS using the .p12 push certificate that you created. If you want to use a notification hub that you have already created, you can skip to step 5.

  1. Log on to the Azure Portal, and then click +NEW at the top left of the screen.
  2. Click on New, then Web + Mobile. Scroll down if necessary and click Notification Hub.

    Azure Portal - Create Notification Hubs

  3. Make sure you specify a unique name in the Notification Hub field. Select your desired Region, Subscription and Resource Group (if you have one already).

    If you already have a service bus namespace that you want to create the hub in, select it through the Select Existing option in the Namespace field. Otherwise, you can use the default name which will be created based on the hub name as long as the namespace name is available.

    Once ready, click Create.

    Azure Portal - Set notification hub properties

  4. Once the namespace and notification hub are created, you will be taken to the respective portal page.

    Azure Portal - Notification hub portal page

  5. Click on Settings and then Access Policies - take note of the two connection strings that are made available to you, as you will need them to handle push notifications later.

    Azure Portal - Notification hub connection strings

  1. As we want to configure the APNS connection, in the Azure Portal, open your Notification Hub settings, ande click on Notification Services, and then click the Apple (APNS) item in the list. Once done, click on Upload Certificate and select the .p12 certificate that you exported earlier, as well as the password for the certificate.

    Make sure to select Sandbox mode since you will be sending push messages in a development environment. Only use the Production setting if you want to send push notifications to users who already purchased your app from the store.

  

  

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 Xamarin Studio, create a new iOS project and select the Unified API > Single View Application template.

    ![Xamarin Studio - Select Application Type][31]
    
  2. Add a reference to the Azure Messaging component. In the Solution view, right-click the Components folder for your project and choose Get More Components. Search for the Azure Messaging component and add the component to your project.
  3. In AppDelegate.cs, add the following using statement:

     using WindowsAzure.Messaging;
    
  4. Declare an instance of SBNotificationHub:

     private SBNotificationHub Hub { get; set; }
    
  5. Create a Constants.cs class with the following variables:

     // Azure app-specific connection string and hub path
     public const string ConnectionString = "<Azure connection string>";
     public const string NotificationHubPath = "<Azure hub path>";
    
  6. In AppDelegate.cs, update FinishedLaunching() to match the following:

     public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
     {
         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;
     }
    
  7. Override the RegisteredForRemoteNotifications() method in AppDelegate.cs:

     public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
     {
         Hub = new SBNotificationHub(Constants.ConnectionString, Constants.NotificationHubPath);
    
         Hub.UnregisterAllAsync (deviceToken, (error) => {
             if (error != null)
             {
                 Console.WriteLine("Error calling Unregister: {0}", error.ToString());
                 return;
             }
    
             NSSet tags = null; // create tags if you want
             Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
                 if (errorCallback != null)
                     Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
             });
         });
     }
    
  8. Override the ReceivedRemoteNotification() method in AppDelegate.cs:

     public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
     {
         ProcessNotification(userInfo, false);
     }
    
  9. 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 (e.g. Airplane) and you want to handle push messaging scenarios specific to your app.

  10. Run the app on your device.

Sending Push Notifications

You can test receiving push notifications in your app by sending notifications in the Azure Portal via the Test Send capability in the Troubleshooting toolset, right in the notification hub page, as shown in the screen below.

Push notifications are normally sent through a back-end service like Mobile Services or ASP.NET using a compatible library. You can also use the REST API directly to send push messages if a library is not available in your scenario.

In this tutorial, we will keep it simple and just demonstrate testing your client app by sending notifications using the .NET SDK for notification hubs in a console application instead of a backend service. We recommend the Use Notification Hubs to push notifications to users tutorial as the next step for sending notifications from an ASP.NET backend. However, the following approaches can be used for sending notifications:

Mobile Apps: For an example of how to send notifications from an Azure App Service Mobile Apps backend that's integrated with Notification Hubs, see Add push notifications to your mobile app.

  • Java / PHP: For an example of how to send push notifications by using the REST APIs, see "How to use Notification Hubs from Java/PHP" (Java | PHP).

(Optional) Send Push Notifications from a .NET Console App

In this section, we will send push notifications by using a simple .NET console app. For the purposes of this example, we will switch to a Windows development environment that has Visual Studio already installed.

  1. In Visual Studio, create a new Visual C# console application:

    ![Visual Studio - Create a new console application][213]
    
  2. In Visual Studio, click Tools, click NuGet Package Manager, and then click Package Manager Console.

    The package manager console should appear docked to the bottom of your Visual Studio workspace.

  3. In the Package Manager Console window, set the Default project to your new console application project, and then in the console window, execute the following command:

     Install-Package Microsoft.Azure.NotificationHubs
    

    This adds a reference to the Azure Notification Hubs SDK using the Microsoft.Azure.Notification Hubs NuGet package.

  4. Open the Program.cs file and add the following using statement, ensuring that we can use Azure classes and functions within your main class:

     using Microsoft.Azure.NotificationHubs;
    
  5. In your Program class, add the following method (don't forget to replace the connection string and hub name):

     private static async void SendNotificationAsync()
     {
         NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
         var alert = "{\"aps\":{\"alert\":\"Hello from .NET!\"}}";
         await hub.SendAppleNativeNotificationAsync(alert);
     }
    
  6. Add the following lines in your Main method:

      SendNotificationAsync();
      Console.ReadLine();
    
  7. Press the F5 key to run the app. Within seconds, you should see a push notification appear on your device. Whether you are using Wi-Fi or a cellular data network, make sure that you have an active internet connection on the device.

You can find all the possible payloads in the Apple Local and Push Notification Programming Guide.

(Optional) Send Notifications from a Mobile Service

In this section, we will send push notifications using a mobile service through a node script.

To send a notification by using a mobile service, follow Get started with Mobile Services, and then:

  1. Sign in to the Azure Classic Portal, and select your mobile service.
  2. Select the Scheduler tab on the top.

    ![Azure Classic Portal - Scheduler][215]
    
  3. Create a new scheduled job, insert a name, and select On demand.

    ![Azure Classic Portal - Create new job][216]
    
  4. When the job is created, click the job name. Then click the Script tab on the top bar.
  5. Insert the following script inside your scheduler function. Make sure to replace the placeholders with your notification hub name and the connection string for DefaultFullSharedAccessSignature that you obtained earlier. Click Save.

     var azure = require('azure');
     var notificationHubService = azure.createNotificationHubService('<Hubname>', '<SAS Full access >');
     notificationHubService.apns.send(
         null,
         {"aps":
             {
               "alert": "Hello from Mobile Services!"
             }
         },
         function (error)
         {
             if (!error) {
                 console.warn("Notification successful");
             }
         }
     );
    
  6. Click Run Once on the bottom bar. You should receive an alert on your device.

Next steps

In this simple example, you broadcasted push notifications to all your iOS devices. In order to target specific users, refer to the tutorial Use Notification Hubs to push notifications to users. If you want to segment your users by interest groups, you can read Use Notification Hubs to send breaking news. Learn more about how to use Notification Hubs in Notification Hubs Guidance and in the Notification Hubs How-To for iOS.