Tutorial: Push notifications to iOS apps using Azure Notification Hubs

In this tutorial, you use Azure Notification Hubs to push notifications to an iOS application. You create a blank iOS app that receives push notifications by using the Apple Push Notification service (APNs).

In this tutorial, you take the following steps:

  • Generate the certificate signing request file
  • Request your app for push notifications
  • Create a provisioning profile for the app
  • Configure your notification hub for iOS push notifications
  • Connect your iOS app to notification hubs
  • Send test push notifications
  • Verify that your app receives notifications

The completed code for this tutorial can be found on GitHub.

Prerequisites

  • An active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes.
  • Windows Azure Messaging Framework
  • Latest version of Xcode
  • An iOS 10 (or later version)-capable device
  • Apple Developer Program membership.

    Note

    Because of configuration requirements for push notifications, you must deploy and test push notifications on a physical iOS device (iPhone or iPad) instead of the iOS Simulator.

Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for 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 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.

  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.

      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.

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

    Clicking on the app ID displays 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.

    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.

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

    It 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 action installs the new certificate in the Keychain, as shown in the following image:

    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 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 + button to create a new profile. You see the Add iOS Provisioning Profile Wizard

  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

  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.

  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 for iOS push notifications

In this section, you create a 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 > Web + 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 your notification hub with APNS information

  1. Under Notification Services, select Apple (APNS).
  2. Select Certificate.
  3. Select the file icon.
  4. Select the .p12 file that you exported earlier.
  5. Specify the correct password.
  6. Select Sandbox mode. Only use the Production if you want to send push notifications to users who purchased your app from the store.

    Configure APNS certification in Azure portal

You have now configured your notification hub with APNS, and you have the connection strings to register your app and send push notifications.

Connect your iOS app to Notification Hubs

  1. In Xcode, create a new iOS project and select the Single View Application template.

    Xcode - Single View Application

  2. When setting the options for your new project, make sure to use the same Product Name and Organization Identifier that you used when you set the bundle identifier in the Apple Developer portal.

    Xcode - project options

  3. Under Project Navigator, click your project name, click the General tab, and find Signing. Make sure you select the appropriate Team for your Apple Developer account. XCode should automatically pull down the Provisioning Profile you created previously based on your bundle identifier.

    If you don't see the new provisioning profile that you created in Xcode, try refreshing the profiles for your signing identity. Click Xcode on the menu bar, click Preferences, click the Account tab, click the View Details button, click your signing identity, and then click the refresh button in the bottom-right corner.

    Xcode - provisioning profile

  4. Select the Capabilities tab and make sure to enable Push Notifications

    Xcode - push capabilities

  5. Download the Windows Azure Messaging Framework and unzip the file. In Xcode, right-click your project and click the Add Files to option to add the WindowsAzureMessaging.framework folder to your Xcode project. Select Options and make sure Copy items if needed is selected, and then click Add.

    Unzip Azure SDK

  6. Add a new header file to your project named HubInfo.h. This file holds the constants for your notification hub. Add the following definitions and replace the string literal placeholders with your hub name and the DefaultListenSharedAccessSignature noted earlier.

        #ifndef HubInfo_h
        #define HubInfo_h
    
            #define HUBNAME @"<Enter the name of your hub>"
            #define HUBLISTENACCESS @"<Enter your DefaultListenSharedAccess connection string"
    
        #endif /* HubInfo_h */
    
  7. Open your AppDelegate.h file add the following import directives:

        #import <WindowsAzureMessaging/WindowsAzureMessaging.h>
        #import <UserNotifications/UserNotifications.h> 
        #import "HubInfo.h"
    
  8. In your AppDelegate.m file, add the following code in the didFinishLaunchingWithOptions method based on your version of iOS. This code registers your device handle with APNs:

        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound |
            UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil];
    
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  9. In the same file, add the following methods:

         - (void) application:(UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *) deviceToken {
           SBNotificationHub* hub = [[SBNotificationHub alloc] initWithConnectionString:HUBLISTENACCESS
                                        notificationHubPath:HUBNAME];
    
            [hub registerNativeWithDeviceToken:deviceToken tags:nil completion:^(NSError* error) {
               if (error != nil) {
                   NSLog(@"Error registering for notifications: %@", error);
                }
                else {
                   [self MessageBox:@"Registration Status" message:@"Registered"];
              }
          }];
         }
    
        -(void)MessageBox:(NSString *) title message:(NSString *)messageText
        {
         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:messageText delegate:self
                cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];
        }
    

    This code connects to the notification hub using the connection information you specified in HubInfo.h. It then gives the device token to the notification hub so that the notification hub can send notifications.

  10. In the same file, add the following method to display a UIAlert if the notification is received while the app is active:

            - (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo {
               NSLog(@"%@", userInfo);
               [self MessageBox:@"Notification" message:[[userInfo objectForKey:@"aps"] valueForKey:@"alert"]];
           }
    
  11. To verify there are no failures, build and 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.

Here is a list of some other tutorials you may want to review for sending notifications:

Verify that your app receives push notifications

To test push notifications on iOS, you must deploy the app to a physical iOS device. You cannot send Apple push notifications by using the iOS Simulator.

  1. Run the app and verify that registration succeeds, and then press OK.

    iOS App Push Notification Registration Test

  2. Next you send a test push notification from the Azure portal, as described in the previous section.

  3. The push notification is sent to all devices that are registered to receive the notifications from the particular Notification Hub.

    iOS App Push Notification Receive Test

Next steps

In this simple example, you broadcasted push notifications to all your registered iOS devices. To learn how to push notifications to specific iOS devices, advance to the following tutorial: