This topic shows you how to use 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.
NOTE:
This topic supports existing mobile services that have not yet been upgraded to use Notification Hubs integration. When you create a new mobile service, this integrated functionality is automatically enabled. For new mobile services, see Get started with push notifications.
Mobile Services integrates with Azure Notification Hubs to support additional push notification functionality, such as templates, multiple platforms, and improved scale. You should upgrade your existing mobile services to use Notification Hubs when possible. Once you have upgraded, see this version of Get started with push notifications.
This tutorial walks you through these basic steps to enable push notifications:
- Generate the certificate signing request
- Register your app and enable push notifications
- Create a provisioning profile for the app
- Configure Mobile Services
- Add push notifications to the app
- Update scripts to send push notifications
- Insert data to receive notifications
This tutorial requires the following:
- Mobile Services iOS SDK
- Xcode 4.5
- An iOS 5.0 (or later version) capable device
- iOS Developer Program membership
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 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.
- From the Utilities folder, run the Keychain Access tool.
- Click Keychain Access, expand Certificate Assistant, then click Request a Certificate from a Certificate Authority....
- 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.
- 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.
- 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.
NOTE:
If you choose to supply a Bundle Identifier value other than MobileServices.Quickstart, you must also update the bundle identifier value in your Xcode project. We recommend that you use the exact bundle identifier value you already used in your quickstart project.
- 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 SubmitOnce you click Submit, you will see the Registration complete screen, as shown below. Click Done.
- 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.
- 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.
- Click Choose File, browse to the location where you saved the CSR file that you created in the first task, then clickGenerate.
- 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.
- 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
- 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
- Select iOS App Development under Development as the provisiong profile type, and click Continue
- Next, select the app ID for the Mobile Services Quickstart app from the App ID drop-down list, and click Continue
- In the Select certificates screen, select the certificate created earlier, and click Continue
- Next, select the Devices to use for testing, and click Continue
- Finally, pick a name for the profile in Profile Name, click Generate, and click DoneThis creates a new provisioning profile.
- 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.
- 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.
- 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.
- 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.
NOTE:
This tutorial creates a QuickstartPusher.p12 file. Your file name and location might be different.
- Log on to the Azure Management Portal, click Mobile Services, and then click your app.
- Click the Push tab and click Upload.This displays the Upload Certificate dialog.
- 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
- In Xcode, open the QSAppDelegate.h file and add the following property below the *window property:
@property (strong, nonatomic) NSString *deviceToken;
- 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; }
- 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]; }
- 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 = @""; }
- 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]; }
- In QSTodoListViewController.m, import the QSAppDelegate.h file so that you can use the delegate to obtain the device token:
#import "QSAppDelegate.h"
- 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.
> [WACOM.NOTE] You must add this code before to the call to the <strong>addItem</strong> method.
Your app is now updated to support push notifications.
Update the registered insert script in the Management Portal
- In the Management Portal, click the Data tab and then click the TodoItem table.
- In todoitem, click the Script tab and select Insert.This displays the function that is invoked when an insert occurs in the TodoItem table.
- 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.
Test push notifications in your app
- Press the Run button to build the project and start the app in an iOS capable device, then click OK to accept push notifications
- In the app, type meaningful text, such as A new Mobile Services task and then click the plus (+) icon.
- Verify that a notification is received, then click OK to dismiss the notification.
- Repeat step 2 and immediately close the app, then verify that the following toast is shown.
You have successfully completed this tutorial.
source from
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-ios-get-started-push/
No comments :
Post a Comment