Pages

Men

rh

10/28/2014

Add push notifications to your Mobile Services app

This topic shows you how to use Azure Mobile Services to send push notifications through Apple Push Notification service (APNS) to an iOS app. In this tutorial, you enable push notifications using Azure Notification Hubs to the quickstart project. When complete, your mobile service will send a push notification each time a record is inserted.
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:
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 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 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 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 Identifiers, then click App IDs, and finally click on the + sign to register a new app.
  1. Type a name for your app in Description, enter the value MobileServices.Quickstart in Bundle Identifier, check the "Push Notifications" option in the "App Services" section, and then click Continue. This example uses the IDMobileServices.Quickstart but you may not reuse this same ID, as app IDs must be unique across all users. As such, it is recommended that you append your full name or initials after the app name.
    This generates your app ID and requests you to Submit the information. Click Submit
    Once you click Submit, you will see the Registration complete screen, as shown below. Click Done.
  2. Locate the app ID that you just created, and click on its row.
    Clicking on the app ID will display details on the app and app ID. Click the Settings button.
  3. 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.
  4. Click Choose File, browse to the location where you saved the CSR file that you created in the first task, then clickGenerate.
  5. After the certificate is created by the portal, click the Download button, and click Done.
    This downloads the signing certificate and saves it to your computer in your Downloads folder.
  6. Double-click the downloaded push certificate aps_development.cer.
    This installs the new certificate in the Keychain, as shown below:
Later, you will use this certificate to generate a .p12 file and upload it to Mobile Services to enable authentication with APNS.

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 for the Mobile Services Quickstart app from the App ID drop-down list, and click Continue
  4. In the Select certificates screen, select the certificate created earlier, and click Continue
  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, and click Done
    This creates a new provisioning profile.
  7. In Xcode, open the Organizer select the Devices view, select Provisioning Profiles in the Library section in the left pane, and then click the Refresh button at the bottom of the middle pane.
  8. Alternatively, from the Xcode menu, select Preferences and then Accounts. Select your Apple Developer ID in the left panel. Click the View Details button on the right. In the pop-over window, click the rounded Refresh button. This refreshes the list of Provisioning profiles. This process may take a few minutes. We recommend that you click Refresh 2-3 times until you see your new provisioning profile. Also, confirm that the bundle identifier of this Xcode project is identical to the bundle identifier associated with the app ID and provisioning profile you've created so far.
  9. 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 Azure.

Configure 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 quickstart app's new certificate in Keys or My Certificates, 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.
  1. Log on to the Azure Management Portal, click Mobile Services, and then click your app.
  2. Click the Push tab and click Upload.
    This displays the Upload Certificate dialog.
  3. Click File, select the exported certificate QuickstartPusher.p12 file, enter the Password, make sure that the correct Mode is selected (either Dev/Sandbox or Prod/Production), click the check icon, then click Save.
Your mobile service is now configured to work with APNS.

Add push notifications to your app

  1. In QSAppDelegate.m, insert the following snippet to import the Mobile Services iOS SDK:
    #import <WindowsAzureMobileServices/WindowsAzureMobileServices.h>
  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. Make sure you copy the Mobile Service URL and Application Key values and switch them in for the placeholders:
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:
    (NSData *)deviceToken {
        // TODO: update @"MobileServiceUrl" and @"AppKey" placeholders
        MSClient *client = [MSClient clientWithApplicationURLString:@"MobileServiceUrl" applicationKey:@"AppKey"];
    
        [client.push registerNativeWithDeviceToken:deviceToken tags:@[@"uniqueTag"] completion:^(NSError *error) {
            if (error != nil) {
                NSLog(@"Error registering for notifications: %@", error);
            }
        }];
    }
  4. In QSAppDelegate.m, add the following handler method inside the implementation:
    // Handle any failure to register.
    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:
    (NSError *)error {
        NSLog(@"Failed to register for remote notifications: %@", error);
    }
  5. In QSAppDelegate.m, add the following handler method inside the implementation:
    // Because 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];
    }
Your app is now updated to support push notifications.

Update 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 push notifications
        setTimeout(function() {
            push.apns.send(null, {
                alert: "Alert: " + 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.

Test 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
  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 push is shown.
You have successfully completed this tutorial.
Source from
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-javascript-backend-ios-get-started-push/

No comments :

Post a Comment