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

In this tutorial, you use Azure Notification Hubs to send 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 complete code for this tutorial can be found on GitHub.

Prerequisites

To complete this tutorial, you need the following prerequisites:

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

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

    Edit App ID page

  6. 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. The same process is used when registering a production certificate. Just make sure that you use the same certificate type when sending notifications.

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

    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.

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

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

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 the .p12 push certificate that you previously created. 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, 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 portal - select Notification Hubs

  3. On the Notification Hubs page, select Add on the toolbar.

    Notification Hubs - Add toolbar button

  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 portal - set notification hub properties

  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 portal - notifications -> Go to resource

  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.

    Important

    Do not use the DefaultFullSharedAccessSignature policy 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, 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.

    Configure APNs certification in Azure portal

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

  3. Under Project Navigator, select your project name under Targets, then select the Signing & Capabilities tab. 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. In the Signing & Capabilities tab, select + Capability. Double-click Push Notifications to enable it.

    Xcode - push capabilities

  5. Add the Azure Notification Hubs SDK modules.

    You can integrate the Azure Notification Hubs SDK in your app by using Cocoapods or by manually adding the binaries to your project.

    • Integration via Cocoapods

      Add the following dependencies to your podfile to include Azure Notification Hubs SDK into your app.

      pod 'AzureNotificationHubs-iOS'
      

      Run pod install to install your newly defined pod and open your .xcworkspace.

      Note

      If you see an error such as [!] Unable to find a specification for AzureNotificationHubs-iOS while running pod install, please run pod repo update to get the latest pods from the Cocoapods repository, and then run pod install.

    • Integration via Carthage

      Add the following dependencies to your Cartfile to include Azure Notification Hubs SDK into your app.

      github "Azure/azure-notificationhubs-ios"
      

      Next, update, and build dependencies:

      $ carthage update
      

      For more information about using Carthage, see the Carthage GitHub repository.

    • Integration by copying the binaries into your project

      1. Download the Azure Notification Hubs SDK framework provided as a zip file and unzip it.

      2. 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 Constants.h. To do so, right-click the project name and select New File.... Then select Header File. This file holds the constants for your notification hub. Then select Next. Name the file Constants.h.

  7. Add the following code to the Constants.h file:

    #ifndef Constants_h
    #define Constants_h
    
    extern NSString* const NHInfoConnectionString;
    extern NSString* const NHInfoHubName;
    extern NSString* const NHUserDefaultTags;
    
    #endif /* Constants_h */
    
  8. Add the implementation file for Constants.h. To do so, right-click the project name and select New File.... Select Objective-C File, and then select Next. Name the file Constants.m.

    Add .m file

  9. Open the Constants.m file and replace its contents with the following code. Replace the string literal placeholders NotificationHubConnectionString and NotificationHubConnectionString with the hub name and the DefaultListenSharedAccessSignature, respectively, as you previously obtained from the portal:

    #import <Foundation/Foundation.h>
    #import "Constants.h"
    
    NSString* const NHInfoConnectionString = @"NotificationHubConnectionString";
    NSString* const NHInfoHubName = @"NotificationHubName";
    NSString* const NHUserDefaultTags = @"notification_tags";
    
  10. Open your project's AppDelegate.h file and replace its contents with the following code:

    #import <UIKit/UIKit.h>
    #import <WindowsAzureMessaging/WindowsAzureMessaging.h>
    #import <UserNotifications/UserNotifications.h> 
    
    @interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
    
    @property (strong, nonatomic) UIWindow *window;
    
    - (void)handleRegister;
    - (void)handleUnregister;
    
    @end
    
    
  11. In the project's AppDelegate.m file, add the following import statements:

    #import "Constants.h"
    #import "NotificationDetailViewController.h"
    
  12. Also in your AppDelegate.m file, add the following line of code in the didFinishLaunchingWithOptions method based on your version of iOS. This code registers your device handle with APNs:

    [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
    
  13. In the same AppDelegate.m file, replace all the code after didFinishLaunchingWithOptions with the following code:

    // Tells the app that a remote notification arrived that indicates there is data to be fetched.
    
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
        NSLog(@"Received remote (silent) notification");
        [self logNotificationDetails:userInfo];
    
        //
        // Let the system know the silent notification has been processed.
        //
        completionHandler(UIBackgroundFetchResultNoData);
    }
    
    // Tells the delegate that the app successfully registered with Apple Push Notification service (APNs).
    
    - (void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        NSMutableSet *tags = [[NSMutableSet alloc] init];
    
        // Load and parse stored tags
        NSString *unparsedTags = [[NSUserDefaults standardUserDefaults] valueForKey:NHUserDefaultTags];
        if (unparsedTags.length > 0) {
            NSArray *tagsArray = [unparsedTags componentsSeparatedByString: @","];
            [tags addObjectsFromArray:tagsArray];
        }
    
        // Register the device with the Notification Hub.
        // If the device has not already been registered, this will create the registration.
        // If the device has already been registered, this will update the existing registration.
        //
        SBNotificationHub* hub = [self getNotificationHub];
        [hub registerNativeWithDeviceToken:deviceToken tags:tags completion:^(NSError* error) {
            if (error != nil) {
                NSLog(@"Error registering for notifications: %@", error);
            } else {
                [self showAlert:@"Registered" withTitle:@"Registration Status"];
            }
        }];
    }
    
    // UNUserNotificationCenterDelegate methods
    //
    // Asks the delegate how to handle a notification that arrived while the app was running in the  foreground.
    
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
        NSLog(@"Received notification while the application is in the foreground");
    
        // The system calls this delegate method when the app is in the foreground. This allows the app to handle the notification
        // itself (and potentially modify the default system behavior).
    
        // Handle the notification by displaying custom UI.
        //
        [self showNotification:notification.request.content.userInfo];
    
        // Use 'options' to specify which default behaviors to enable.
        // - UNAuthorizationOptionBadge: Apply the notification's badge value to the app’s icon.
        // - UNAuthorizationOptionSound: Play the sound associated with the notification.
        // - UNAuthorizationOptionAlert: Display the alert using the content provided by the notification.
        //
        // In this case, do not pass UNAuthorizationOptionAlert because the notification was handled by the app.
        //
        completionHandler(UNAuthorizationOptionBadge | UNAuthorizationOptionSound);
    }
    
    // Asks the delegate to process the user's response to a delivered notification.
    //
    
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
        NSLog(@"Received notification while the application is in the background");
    
        // The system calls this delegate method when the user taps or responds to the system notification.
    
        // Handle the notification response by displaying custom UI
        //
        [self showNotification:response.notification.request.content.userInfo];
    
        // Let the system know the response has been processed.
        //
        completionHandler();
    }
    
    // App logic and helpers
    
    - (SBNotificationHub *)getNotificationHub {
        NSString *hubName = [[NSBundle mainBundle] objectForInfoDictionaryKey:NHInfoHubName];
        NSString *connectionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:NHInfoConnectionString];
    
        return [[SBNotificationHub alloc] initWithConnectionString:connectionString notificationHubPath:hubName];
    }
    
    - (void)handleRegister {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    
        UNAuthorizationOptions options =  UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
        [center requestAuthorizationWithOptions:(options) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (error != nil) {
                NSLog(@"Error requesting for authorization: %@", error);
            }
        }];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    
    - (void)handleUnregister {
        //
        // Unregister the device with the Notification Hub.
        //
        SBNotificationHub *hub = [self getNotificationHub];
        [hub unregisterNativeWithCompletion:^(NSError* error) {
            if (error != nil) {
                NSLog(@"Error unregistering for push: %@", error);
            } else {
                [self showAlert:@"Unregistered" withTitle:@"Registration Status"];
            }
        }];
    }
    
    - (void)logNotificationDetails:(NSDictionary *)userInfo {
        if (userInfo != nil) {
            UIApplicationState state = [UIApplication sharedApplication].applicationState;
            BOOL background = state != UIApplicationStateActive;
            NSLog(@"Received %@notification: \n%@", background ? @"(background) " : @"", userInfo);
        }
    }
    
    - (void)showAlert:(NSString *)message withTitle:(NSString *)title {
        if (title == nil) {
            title = @"Alert";
        }
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alert animated:YES completion:nil];
    }
    
    - (void)showNotification:(NSDictionary *)userInfo {
        [self logNotificationDetails:userInfo];
    
        NotificationDetailViewController *notificationDetail = [[NotificationDetailViewController alloc] initWithUserInfo:userInfo];
        [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:notificationDetail animated:YES completion:nil];
    }
    
    @end
    

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

NotificationDetailViewController

  1. Similar the previous instructions, add another header file named NotificationDetailViewController.h. Replace the contents of the new header file with the following code:

    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface NotificationDetailViewController : UIViewController
    
    @property (strong, nonatomic) IBOutlet UILabel *titleLabel;
    @property (strong, nonatomic) IBOutlet UILabel *bodyLabel;
    @property (strong, nonatomic) IBOutlet UIButton *dismissButton;
    
    @property (strong, nonatomic) NSDictionary *userInfo;
    
    - (id)initWithUserInfo:(NSDictionary *)userInfo;
    
    @end
    
    NS_ASSUME_NONNULL_END
    
  2. Add the implementation file NotificationDetailViewController.m. Replace the contents of the file with the following code, which implements the UIViewController methods:

    #import "NotificationDetailViewController.h"
    
    @interface NotificationDetailViewController ()
    
    @end
    
    @implementation NotificationDetailViewController
    
    - (id)initWithUserInfo:(NSDictionary *)userInfo {
        self = [super initWithNibName:@"NotificationDetail" bundle:nil];
        if (self) {
            _userInfo = userInfo;
        }
        return self;
    }
    
    - (void)viewDidLayoutSubviews {
        [self.titleLabel sizeToFit];
        [self.bodyLabel sizeToFit];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        NSString *title = nil;
        NSString *body = nil;
    
        NSDictionary *aps = [_userInfo valueForKey:@"aps"];
        NSObject *alertObject = [aps valueForKey:@"alert"];
        if (alertObject != nil) {
            if ([alertObject isKindOfClass:[NSDictionary class]]) {
                NSDictionary *alertDict = (NSDictionary *)alertObject;
                title = [alertDict valueForKey:@"title"];
                body = [alertObject valueForKey:@"body"];
            } else if ([alertObject isKindOfClass:[NSString class]]) {
                body = (NSString *)alertObject;
            } else {
                NSLog(@"Unable to parse notification content. Unexpected format: %@", alertObject);
            }
        }
    
        if (title == nil) {
            title = @"<unset>";
        }
    
        if (body == nil) {
            body = @"<unset>";
        }
    
        self.titleLabel.text = title;
        self.bodyLabel.text = body;
    }
    
    - (IBAction)handleDismiss:(id)sender {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    @end
    

ViewController

  1. In the project's ViewController.h file, add the following import statements:

    #import <WindowsAzureMessaging/WindowsAzureMessaging.h>
    #import <UserNotifications/UserNotifications.h>
    
  2. Also in ViewController.h, add the following property declarations after the @interface declaration:

    @property (strong, nonatomic) IBOutlet UITextField *tagsTextField;
    @property (strong, nonatomic) IBOutlet UIButton *registerButton;
    @property (strong, nonatomic) IBOutlet UIButton *unregisterButton;
    
  3. In the project's ViewController.m implementation file, replace the contents of the file with the following code:

    #import "ViewController.h"
    #import "Constants.h"
    #import "AppDelegate.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    // UIViewController methods
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        // Simple method to dismiss keyboard when user taps outside of the UITextField.
        [self.view endEditing:YES];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        // Load raw tags text from storage and initialize the text field
        self.tagsTextField.text = [[NSUserDefaults standardUserDefaults] valueForKey:NHUserDefaultTags];
    }
    
    - (IBAction)handleRegister:(id)sender {
        // Save raw tags text in storage
        [[NSUserDefaults standardUserDefaults] setValue:self.tagsTextField.text forKey:NHUserDefaultTags];
    
    // Delegate processing the register action to the app delegate.
    [[[UIApplication sharedApplication] delegate] performSelector:@selector(handleRegister)];
    }
    
    - (IBAction)handleUnregister:(id)sender {
        [[[UIApplication sharedApplication] delegate] performSelector:@selector(handleUnregister)];
    }
    
    @end
    
  4. 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 isn't 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 might 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: