Smarter ideas worth writing about.

Pushing with Azure

Background

What are push notifications? Smartphones and tablets are able to “notify” users when an event has occurred or new data is available. All major platforms support some variation of push notifications. These notifications can be sent both when the device is away and asleep.

Push notifications in Azure are delivered via a platform-specific infrastructure that extends from a bare bone system called Platform Notification System (PNS). Each platform, Apple, Google, and Windows Phone, sends to their respective PNS’s.  Azure has two distinct mechanisms to send notifications to devices, the standard push pattern and notification hubs. Using the standard notification pattern you, as the developer, are responsible for the complete cycle of pushes minus the connection to the platform specific PNS. Where as with notifications hub you simply implement the Azure notification hub API. We will see this in a few moments.

In this example we will be talking about notification hubs and how to harness the power to simplify push notifications in an iOS mobile application.

Example

Note: This post assumes you have familiarity with generating push certificates and signing applications in the Apple ecosystem.

Once we have generated our push certificates and application identity we can start setting up our Azure notification hubs. 

1. The first step is to log into our Azure Management Portal and create a new notification hub. 

2. You will need to name your notification hub. After it is created you will see it listed in the service bus section of the Azure Management Portal.

3. You will then need to click in the hub you just created. If you have created a mobile service and enabled pushes a notification hub will have already been created when you enabled enhanced pushes.

4. Select the notification hub to open its details, click on the configure tab at the top.This is where you will see all the different options for push certificates. In the iOS section there is an upload button. Click this and it will open the upload dialog. You will select the certificate you generated in the iOS developer portal and on the development mac. You can select either production or sandbox certificate. At this time, notification hubs have an issue where when you change certificates you have to delete and recreate the notification hub.

5. You will then need to get the connection string information for the notification hub for the iOS app.

iOS App 

To modify the iOS app to use the notification hub for pushes we first start in the AppDelegate. We need to first import the WindowsAzureMessage framework into the project.

#import <WindowsAzureMessaging/WindowsAzureMessaging.h>

Once we have the framework imported into the project we need to tell the app that we want to register for notifications. We do this by using the following code:

[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];

In the app delegate, implement the didRegisterForRemoteNotificationWithDeviceToken: and add the following code:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *) deviceToken {    
    SBNotificationHub* hub = [[SBNotificationHub alloc] initWithConnectionString:
                              @"<connection string>" notificationHubPath:@"mynh"];

    [hub registerNativeWithDeviceToken:deviceToken tags:nil completion:^(NSError* error) {
        if (error != nil) {
            NSLog(@"Error registering for notifications: %@", error);
        }
    }];
}

The connection string is what you gathered from the previous steps above when setting up the notification hub. The notificationHubPath is the name of the notification hub you crated in Azure. This method calls the notification to register with the notification hub. In this specific instance we are registering the device with no Tag. A unique feature of notification hubs is that a device can be registered with one or more tags. This allows Azure to push to a group of tags or all users. 

The final step in the iOS app is to add the method that handles the notification, didReceiveRemoteNotification: is that such method. 

- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo {
    NSLog(@"%@", userInfo);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notification" message:
    [[userInfo objectForKey:@"aps"] valueForKey:@"alert"] delegate:nil cancelButtonTitle:
    @"OK" otherButtonTitles:nil, nil];
    [alert show];
}

Azure Backend

Now that the app is setup to register with the notification hub we need a method to send notifications. In this case we are going to use NodeJS as Mobile API in Azure to send them.

The first step in the NodeJS script is to create our connection to the notification hub. We can do this using these two lines.

var iosMessage = {
            alert: Title,
            payload : {
                inAppMessage:Message Sent
            },
            sound : Default
        };

In the NodeJS script we can now create our iOS message that is to be pushed. We will set this up using Nodes built-in dictionary object with keyword. This is a simple example that crates a notification with the title of “Title” and a message of “Message Sent."

    notificationHubService.apns.send(
        Tag or null,
        iosMessage,
        function (error) {
            if (!error) {
              console.info("iOS Notification successful: ", response);
            } else {
                console.warn("iOS Notification failed " + error);
            }
        }
    );

Now sending the notification is very simple using Node. Calling the notificationHubService created above. You access the apple push notification service platform. This is a platform that is created for you. You then call the send method passing in a list of up to 20 tags or null. If you pass a tag notification hub will only send it to those devices registered with the specified tags. If null is passed the push will register all devices in the notification hub. You will get a response that you can check if the pushes were sent to Apple successfully.

    notificationHubService.apns.send(
        Tag or null,
        iosMessage,
        function (error) {
            if (!error) {
              console.info("iOS Notification successful: ", response);
            } else {
                console.warn("iOS Notification failed " + error);
            }
        }
    );

Conclusion

As we have seen, notifications can be added to an iOS app that uses Azure in a quick and efficient manner. The same goes for Windows Phone and Android. We can also harness the power of tags to specify pushes to groups or individuals. Thedownside to using notification hub is that through the typical web interface there is no way to handle device registration or even view which platforms are registered in your hub. There is a handy tool by Paolo Salvatori from Microsoft that allows exploring notification hubs and views much more details about them. You can read more about it at: http://code.msdn.microsoft.com/windowsazure/Service-Bus-Explorer-f2abca5a.

Share:

About The Author

Principal Consultant I
Eric is a Principal Developer in Cardinal's Cincinnati office who is focused on pushing the envelope technically and creatively in mobile application development.