Free trial *Internet Service Required

Get started with push notifications in Mobile Services

This topic shows you how to use Windows Azure Mobile Services to send push notifications to an iOS app. In this tutorial you add push notifications using the Apple Push Notification service (APNS) to the quickstart project. When complete, your mobile service will send a push notification each time a record is inserted.

You can watch a video version of this tutorial by clicking the clip to the right.

Note

This tutorial demonstrates a simplified way of sending push notifications by attaching a push notification device token to the inserted record. Be sure to follow along with the next tutorial to get a better idea of how to incorporate push notifications into your real-world apps.

This tutorial walks you through these basic steps to enable push notifications:

  1. Generate the certificate signing request
  2. Register your app and enable push notifications
  3. Create a provisioning profile for the app
  4. Configure Mobile Services
  5. Add push notifications to the app
  6. Update scripts to send push notifications
  7. Insert data to receive notifications

This tutorial requires the following:

Note

Because of push notification configuration requirements, you must deploy and test push notifications on an iOS capable device (iPhone or iPad) instead of in the emulator.

This tutorial is based on the Mobile Services quickstart. Before you start this tutorial, you must first complete Get started with Mobile Services.

The Apple Push Notification Service (APNS) uses certificates to authenticate your mobile service. Follow these instructions to create the necessary certificates and upload it to your Mobile Service. For the official APNS feature documentation, see Apple Push Notification Service.

Generate CSR fileGenerate the Certificate Signing Request file

First you must generate the Certificate Signing Request (CSR) file, which is used by Apple to generate a signed certificate.

  1. From the Utilities folder, run the Keychain Access tool.

  2. Click Keychain Access, expand Certificate Assistant, then click Request a Certificate from a Certificate Authority....

  3. Select your User Email Address, type Common Name and CA Email Address values, make sure that Saved to disk is selected, and then click Continue.

  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 appRegister your app for push notifications

To be able to send push notifications to an iOS app from mobile services, 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 App IDs, then click New App ID.

  2. Type a name for your app in Description, enter the value MobileServices.Quickstart in Bundle Identifier, then click Submit.

    This generates your app ID.

    Note

    If you choose to supply a Bundle Identifier value other thanMobileServices.Quickstart, you must also update the bundle identifier value in your Xcode project.

  3. Locate the app ID that you just created, then click Configure.

  4. Check the Enable for Apple Push Notification service check box, then click the Continue button for the Development Push SSL Certificate.

    This displays the Apple Push Notification service SSL Certificate Assistant.

    Note

    This tutorial uses a development certificate. The same process is used when registering a production certificate. Just make sure that you set the same certificate type when you upload the certificate to Mobile Services.

  5. Click Browse, 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 Continue and on the next screen click Download.

    This downloads the signing 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 Notification Services:.

Later, you will use this certificate to generate a .p12 file and upload it to Mobile Services to enable authentication with APNS.

Provision the appCreate a provisioning profile for the app

  1. Back in the iOS Provisioning Portal, select Provisioning, then click New Profile.

  2. Enter a Profile Name, select the Certificates and Devices to use for testing, select the App ID, then click Submit.

    This creates a new provisioning profile.

  3. From the list of provisioning profiles, click the Download button for this new profile.

    This downloads the profile to the local computer.

    Note

    You may need to refresh the page to see the new profile.

  4. In Xcode, open the Organizer select the Devices view, select Provisioning Profiles in the Library section in the left pane, and then click the Import button at the very bottom of the middle pane.

  5. Locate the downloaded provisioning profile and click Open.

  6. Under Targets, click Quickstart, expand Code Signing Identity, then under Debug select the new profile.

This ensures that the Xcode project uses the new profile for code signing. Next, you must upload the certificate to Mobile Services.

Configure the serviceConfigure Mobile Services to send push requests

After you have registered your app with APNS and configured your project, you must next configure your mobile service to integrate with APNS.

  1. In Keychain Access, right-click the new certificate, click Export, name your file QuickstartPusher, select the .p12 format, then click Save.

    Make a note of the file name and location of the exported certificate.

    Note

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

  2. Log on to the Windows Azure Management Portal, click Mobile Services, and then click your app.

  3. Click the Push tab and click Upload.

    This displays the Upload Certificate dialog.

  4. Click File, select the exported certificate QuickstartPusher.p12 file, enter the Password, make sure that the correct Mode is selected, click the check icon, then click Save.

    Note

    This tutorial uses developement certificates.

Both your mobile service is now configured to work with APNS.

Add push notificationsAdd push notifications to your app

  1. In Xcode, open the QSAppDelegate.h file and add the following property below the *window property:

    @property (strong, nonatomic) NSString *deviceToken;
    Note

    When dynamic schema is enabled on your mobile service, a new 'deviceToken' column is automatically added to the TodoItem table when a new item that contains this property is inserted.

  2. In QSAppDelegate.m, replace the following handler method inside the implementation:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
    (NSDictionary *)launchOptions
    {
        // Register for remote notifications
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
        UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
        return YES;
    }
  3. In QSAppDelegate.m, add the following handler method inside the implementation:

    // We are registered, so now store the device token (as a string) on the AppDelegate instance
    // taking care to remove the angle brackets first.
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:
    (NSData *)deviceToken {
        NSCharacterSet *angleBrackets = [NSCharacterSet characterSetWithCharactersInString:@"<>"];
        self.deviceToken = [[deviceToken description] stringByTrimmingCharactersInSet:angleBrackets];
    }
  4. In QSAppDelegate.m, add the following handler method inside the implementation:

    // Handle any failure to register. In this case we set the deviceToken to an empty
    // string to prevent the insert from failing.
    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:
    (NSError *)error {
        NSLog(@"Failed to register for remote notifications: %@", error);
        self.deviceToken = @"";
    }
  5. In QSAppDelegate.m, add the following handler method inside the implementation:

    // Because toast alerts don't work when the app is running, the app handles them.
    // This uses the userInfo in the payload to display a UIAlertView.
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:
    (NSDictionary *)userInfo {
        NSLog(@"%@", userInfo);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notification" message:
        [userInfo objectForKey:@"inAppMessage"] delegate:nil cancelButtonTitle:
        @"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
  6. In QSTodoListViewController.m, import the QSAppDelegate.h file so that you can use the delegate to obtain the device token:

    #import "QSAppDelegate.h"
  7. In QSTodoListViewController.m, modify the (IBAction)onAdd action by locating the following line:

    NSDictionary *item = @{ @"text" : itemText.text, @"complete" : @(NO) };

    Replace this with the following code:

    // Get a reference to the AppDelegate to easily retrieve the deviceToken
    QSAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    
    
    NSDictionary *item = @{
        @"text" : itemText.text,
        @"complete" : @(NO),
        // add the device token property to our todo item payload
        @"deviceToken" : delegate.deviceToken
    };

    This adds a reference to the QSAppDelegate to obtain the device token and then modifies the request payload to include that device token.

Note

You must add this code before to the call to the addItem method.

Your app is now updated to support push notifications.

Update the insert scriptUpdate the registered insert script in the Management Portal

  1. In the Management Portal, click the Data tab and then click the TodoItem table.

  2. In todoitem, click the Script tab and select Insert.

    This displays the function that is invoked when an insert occurs in the TodoItem table.

  3. Replace the insert function with the following code, and then click Save:

    function insert(item, user, request) {
        request.execute();
        // Set timeout to delay the notification, to provide time for the 
        // app to be closed on the device to demonstrate toast notifications
        setTimeout(function() {
            push.apns.send(item.deviceToken, {
                alert: "Toast: " + item.text,
                payload: {
                    inAppMessage: "Hey, a new item arrived: '" + item.text + "'"
                }
            });
        }, 2500);
    }

    This registers a new insert script, which uses the apns object to send a push notification (the inserted text) to the device provided in the insert request.

Note

This script delays sending the notification to give you time to close the app to receive a toast notification.

Test the appTest push notifications in your app

  1. Press the Run button to build the project and start the app in an iOS capable device, then click OK to accept push notifications

    Note

    You must explicitly accept push notifications from your app. This request only occurs the first time that the app runs.

  2. In the app, type meaningful text, such as A new Mobile Services task and then click the plus (+) icon.

  3. Verify that a notification is received, then click OK to dismiss the notification.

  4. Repeat step 2 and immediately close the app, then verify that the following toast is shown.

You have successfully completed this tutorial.

Next steps

In this simple example a user receives a push notification with the data that was just inserted. The device token used by APNS is supplied to the mobile service by the client in the request. In the next tutorial, Push notifications to app users, you will create a separate Devices table in which to store device tokens and send a push notification out to all stored channels when an insert occurs.

Rss Newsletter