Wednesday, 30 November 2016

Push Notifications for Ionic App


  •  2016-08-25
  •  887
This guide aims to help you set up push notifications for your Ionic app. Also I will append new questions to the final help section for something like the FAQ of Ionic push notifications. Without more words, let’s start the fun.
It’s going to be a wild ride!
Oh and if you want to grab a Postman collection with all the HTTP Requests you need for creating and observing Push notifications, just enter you email below!

Start the smallest Push App ever

The funny thing here is that we actually need almost no code for push to work. Anyway, we start with a blank Ionic app and add 2 plugins, the ionic-platform-web-client which will handle the connection to Ionic.io and the phonegap-plugin-push which handles incoming pushes inside your app (and how you want to react upon receiving them). So go ahead and run:
Start a blank Ionic project and add needed plugins
ionic start devdactic-push blank
cd devdactic-push
ionic add ionic-platform-web-client
ionic plugin add phonegap-plugin-push --variable SENDER_ID="GCM_PROJECT_NUMBER"
We need a GCM project number for our Android app, but as we currently haven’t created something like this you can simply add it with the dummy string, or leave the part with –variable… out for now.
When I installed the plugin I got this error:
_
Plugin doesn’t support this project’s cordova-ios version. cordova-ios: 3.8.0, failed version requirement: >=4.0.0_
If you encounter this as well, here is the fix to install the right iOS platform:
Fix the platform error
ionic platform rm ios
ionic platform add ios@4.1.0
Alright, the basic is done, let’s connect our app to the Ionic.io services!
If you have no account there, now is the time. It’s free and you need it in order to send Ionic push notifications to your app.
Your account is ready?
Then continue on your command line and run:
Connect your App with Ionic.io and enable DEV PUSH
ionic io init
ionic config set dev_push true
First of all this will create an app id inside your Ioni.io dashboard, and we also enable Dev Pushes for our app to test if everything works until now. The name Dev Push is not really good and afaik they think about changing it to to Demo Push, hope we see that change soon!
The funny part is now the code we actually need. Open up your app.js and replace the current .run() block with this:
Everything you need inside app.js
angular.module('starter', ['ionic'])
 
.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    var push = new Ionic.Push({
      "debug": true
    });
 
    push.register(function(token) {
      console.log("My Device token:",token.token);
      push.saveToken(token);  // persist the token in the Ionic Platform
    });
  });
})
We could actually leave out more lines, but I think this is fine for now. We create a new Push object and register ourself. On success, we will log our device token which we need to send push notifications to.
And that’s everything we need right now, so let’s see our app in action.

Creating Ionic Demo Push Notifications

To test our app we want to use the Dev Push, but before we need to add a security profile and create an API keyinside Ionic.io so that we can contact the services from outside.
So go to your created App inside the Ionic.io dashboard, click on Settings and in the submenu Certificates. We need to create a profile now, otherwise for me the push was not recognized (although it should work without a profile in this step, and previously did).
Anyway, we need this profile later for our iOS and Android certificates so go ahead and add one right now. I named mine test and the result looks like this:
ionic-security-profile
As said before we also need an API key to talk to the Ionic.io services from outside, so now go to API Keys and create a New API Token in the upper section of the page.
ionic-api-token
Now we are already able to send our Dev Push, so go ahead and run your app with ionic serve or on a device, and observe the log for our Dev Token!
Now we can send a push using a CURL request, the 3 things you need to have are:
  • DEV_DEVICE_TOKEN: The one you copied from your apps log
  • PROFILE_NAME: The name of your security profile
  • API_TOKEN: The API token you created
Insert those values into the command below, run it and you should see a message coming up in your browser!
Create a test Push
curl -X POST -H "Authorization: Bearer API_TOKEN" -H "Content-Type: application/json" -d '{
    "tokens": ["DEV_DEVICE_TOKEN"],
    "profile": "PROFILE_NAME",
    "notification": {
        "message": "This is my demo push!"
    }
}' "https://api.ionic.io/push/notifications"
If you want it a bit more comfortable, I can recommend making those request with Postman, an awesome tool for testing APIs. The calls inside Postman for creating a dev push would look like the following.
The Body section of our push:
postman-push-body
The Headers for our notification:
postman-push-header

Setting up Ionic Push Notifications Profiles

To use the platform specific services of Apple and Google we need to configure some profiles and stuff, but the integration within Ionic.io has really become a lot easier by now. So let’s take a closer look at both platforms (or pick just he one you need!).

iOS

The Ionic team offers a very detailed guide on how to create the profiles you need, so I recommend you stick completely to this documentation on iOS Push Profiles.
Also, to generate these certificates you need a Mac and also need to be part of the Apple Developer Program. If you just joined now, you might also need to set up your general iOS Build Profiles, but you don’t need this step if you have already previously created iOS apps.
After going through the Push guide you need to have your App Id from the Identifier you created inside your Apple profile. Copy that ID and open your config.xml and add your ID:
Add your iOS App ID
<widget id="YOU_APP_ID" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
This is important because now your build iOS app will also have that bundle ID, which it needs to receive our pushes.
The last thing for iOS you need now is to upload the needed certificate into your Ionic.io security profile. You might have already done this as a final step of the Ionic guide, so just make sure that inside your security profile the Push Notification Service is set up correctly like this:
ios-security-profile

Android

The setup for Android is even a bit easier, because the certificate-signing-provisioning stuff get’s a lot easier. For Android you need to be inside the Google Developers program, and you also need to set up some basic keys (if you have never created Android apps before) using this documentation from Ionic.
If you have already worked with Android apps before you can skip that step.
The next step is to create a Google API project inside your dashboard and enabling Google Cloud Messaging. As I can’t describe it any better, please follow the advise on Android Push Profiles from Ionic.
After going through this steps you should have already added the API Key to your Ionic.io security profile (if not do now) and the result should look like this:
android-security-profile
The last thing we need to change now is the GCM number for our
– set GCM number for your project phonegap-plugin-push which we installed in the beginning with a dummy value. To make sure everything works correctly I recommend you remove the plugin and add it again but now with your GCM_PROJECT_NUMBER (which you can find inside your Google Dashboard). Also you n eed to add the android platform if you haven’t done already.
Add the plugin with the correct GCM Key
ionic platform add android
ionic plugin rm phonegap-plugin-push
ionic plugin add phonegap-plugin-push --variable SENDER_ID="GCM_PROJECT_NUMBER"
ionic config set gcm_key <your-gcm-project-number>

Send Real Ionic Push Notifications

Everything until here was smooth sailing and not the real world (ok maybe the Apple certificates very a bit hard). It’s time to get real, so start on your command line and set our Dev Push to false:
Set DEV PUSH to false to use real push notifications
ionic config set dev_push false
**
From now on, we can only test our real Android and iOS Push Notifications on a real device!**
Also, in order to see that we got the push you currently need to close the app to get a notification because the Push inside an open app will be handled directly. If you app is closed you can see the little banner at the top, so that’s what we want to see if everything ins working.

iOS

For iOS I recommend you simply build the app using ionic build ios and afterwards open the Xcode project. Why?
Because we need the log message of our token. And I often had a hard time getting to the log using a different method than this.
So if you run your app, you should find your device token inside the log. With that, and all the information you already had before, you can create a Push using the CURL or Postman commands we already had in the beginning. The result should look like this on an iPhone:
ionic-ios-push

Android

Coming from a native iOS background, Android was a bit tricky for me, especially getting the device token.
So after running ionic build android you should find your APK inside platforms/android/build/outputs/apk/YOURAPP.apk.
If you connect your Android device to your computer, you can now run adb install PATH_TO_YOUR_APP and have the app directly on your device.
Finally, we also need the device token, so I opened the Android Device Monitor running just monitor from the command line.
Inside the logs (have fun filtering for the right logs of your app!) you can find the token after the app starts somewhere in the onRegistration block just like in the image below.
android-ddms-pushtoken
With that token, you can again perform the create push call using CURL or Postman and the result on Android looks like this (maybe cooler background on your device):
ionic-android-push

Ionic Push Notifications Help Section

Ok so there you have it, the complete setup guide for Ionic Push Notifcations. This last section is now meant to help with some general problems you might encounter along the way.
This section will be updated with new questions and problems you have!

Cordova Push Plugin Behaviour

If you want to change the behaviour of how a push is handled inside your app and what options you also have, check out the Github repo of the phonegap-plugin-push .

HTTP Error Codes

When you create your pushes and don’t receive anything on your device, you should always check the status of the created push using the UUID you get after making the POST. This helped me a lot to troubleshoot what was going on, and you can find a list for all the error codes inside the Ionic documentation.

Add push notifications to your Apache Cordova app

Overview

In this tutorial, you add push notifications to the Apache Cordova quick start project so that a push notification is sent to the device every time a record is inserted.
If you do not use the downloaded quick start server project, you will need the push notification extension package. See Work with the .NET backend server SDK for Azure Mobile Apps for more information.

Prerequisites

This tutorial covers an Apache Cordova application developed with Visual Studio 2015 that runs on the Google Android Emulator, an Android device, a Windows device, and an iOS device.
To complete this tutorial, you need:

Configure a notification hub

App Service Mobile Apps uses Notification Hubs to send pushes, so you will be configuring a notification hub for your mobile app.
  1. In Azure Portal, go to App Services, then click your app backend. Under Settings, click Push.
  2. Click Connect to add a notification hub resource to the app. You can either create a hub or connect to an existing one.
Now you have connected a notification hub to your Mobile App backend. Later you will configure this notification hub to connect to a platform notification system (PNS) to push to devices.

Update the server project to send push notifications

In this section, you update code in your existing Mobile Apps backend project to send a push notification every time a new item is added. This is powered by Notification Hubs' template feature, enabling cross-platform pushes. The various clients are registered for push notifications using templates, and a single universal push can get to all client platforms.
Choose the procedure below that matches your backend project type—either .NET backend or Node.js backend.

.NET backend project

  1. In Visual Studio, right-click the server project and click Manage NuGet Packages, search for Microsoft.Azure.NotificationHubs, then click Install. This installs the Notification Hubs library for sending notifications from your backend.
  2. In the server project, open Controllers > TodoItemController.cs, and add the following using statements:
    Copy
     
     using System.Collections.Generic;
     using Microsoft.Azure.NotificationHubs;
     using Microsoft.Azure.Mobile.Server.Config;
    
  3. In the PostTodoItem method, add the following code after the call to InsertAsync:
    Copy
     
     // Get the settings for the server project.
     HttpConfiguration config = this.Configuration;
     MobileAppSettingsDictionary settings = 
         this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
    
     // Get the Notification Hubs credentials for the Mobile App.
     string notificationHubName = settings.NotificationHubName;
     string notificationHubConnection = settings
         .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
    
     // Create a new Notification Hub client.
     NotificationHubClient hub = NotificationHubClient
     .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
     // Sending the message so that all template registrations that contain "messageParam"
     // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
     Dictionary<string,string> templateParams = new Dictionary<string,string>();
     templateParams["messageParam"] = item.Text + " was added to the list.";
    
     try
     {
         // Send the push notification and log the results.
         var result = await hub.SendTemplateNotificationAsync(templateParams);
    
         // Write the success result to the logs.
         config.Services.GetTraceWriter().Info(result.State.ToString());
     }
     catch (System.Exception ex)
     {
         // Write the failure result to the logs.
         config.Services.GetTraceWriter()
             .Error(ex.Message, null, "Push.SendAsync Error");
     }
    
    This sends a template notification that contains the item.Text when a new item is inserted.
  4. Republish the server project.

Node.js backend project

  1. If you haven't already done so, download the quickstart backend project or else use the online editor in the Azure portal.
  2. Replace the existing code in todoitem.js with the following:
    Copy
     
     var azureMobileApps = require('azure-mobile-apps'),
     promises = require('azure-mobile-apps/src/utilities/promises'),
     logger = require('azure-mobile-apps/src/logger');
    
     var table = azureMobileApps.table();
    
     table.insert(function (context) {
     // For more information about the Notification Hubs JavaScript SDK, 
     // see http://aka.ms/nodejshubs
     logger.info('Running TodoItem.insert');
    
     // Define the template payload.
     var payload = '{"messageParam": "' + context.item.text + '" }';  
    
     // Execute the insert.  The insert returns the results as a Promise,
     // Do the push as a post-execute action within the promise flow.
     return context.execute()
         .then(function (results) {
             // Only do the push if configured
             if (context.push) {
                 // Send a template notification.
                 context.push.send(null, payload, function (error) {
                     if (error) {
                         logger.error('Error while sending push notification: ', error);
                     } else {
                         logger.info('Push notification sent successfully!');
                     }
                 });
             }
             // Don't forget to return the results from the context.execute()
             return results;
         })
         .catch(function (error) {
             logger.error('Error while running context.execute: ', error);
         });
     });
    
     module.exports = table;  
    
    This sends a template notification that contains the item.text when a new item is inserted.
  3. When editing the file on your local computer, republish the server project.

Modify your Cordova app to receive push notifications

You must make sure that your Apache Cordova app project is ready to handle push notifications by installing the Cordova push plugin plus any platform-specific push services.

Update the Cordova version in your project.

We recommended that you update the client project to Cordova 6.1.1 if your project is configured using an older version. To update the project, right-click config.xml to open the configuration designer. Select the Platforms tab and choose 6.1.1 in the Cordova CLI text box.
Choose Build, then Build Solution to update the project.

Install the push plugin

Apache Cordova applications do not natively handle device or network capabilities. These capabilities are provided by plugins that are published either on npm or on GitHub. The phonegap-plugin-push plugin is used to handle network push notifications.
You can install the push plugin in one of these ways:
From the command-prompt:
Execute the following command:
Copy
 
cordova plugin add phonegap-plugin-push
From within Visual Studio:
  1. In Solution Explorer, open the config.xml file click Plugins > Custom, select Git as the installation source, then enter https://github.com/phonegap/phonegap-plugin-push as the source.
  2. Click on the arrow next to the installation source.
  3. In SENDER_ID, if you already have a numeric project ID for the Google Developer Console project, you can add it here. Otherwise, enter a placeholder value, like 777777, and if you are targeting Android you can update this value in config.xml later.
  4. Click Add.
The push plugin is now installed.

Install the device plugin

Follow the same procedure you used to install the push plugin, but you will find the Device plugin in the Core plugins list (click Plugins > Core to find it). You need this plugin to obtain the platform name (device.platform).

Register your device for push on start-up

Initially, we will include some minimal code for Android. Later, we will make some small modifications to run on iOS or Windows 10.
  1. Add a call to registerForPushNotifications during the callback for the login process, or at the bottom of the onDeviceReady method:
    Copy
     
     // Login to the service.
     client.login('google')
         .then(function () {
             // Create a table reference
             todoItemTable = client.getTable('todoitem');
    
             // Refresh the todoItems
             refreshDisplay();
    
             // Wire up the UI Event Handler for the Add Item
             $('#add-item').submit(addItemHandler);
             $('#refresh').on('click', refreshDisplay);
    
                 // Added to register for push notifications.
             registerForPushNotifications();
    
         }, handleError);
    
    This example shows calling registerForPushNotifications after authentication succeeds, which is recommended when using both push notifications and authentication in your app.
  2. Add the new registerForPushNotifications method as follows:
    Copy
     
     // Register for Push Notifications. Requires that phonegap-plugin-push be installed.
     var pushRegistration = null;
     function registerForPushNotifications() {
       pushRegistration = PushNotification.init({
           android: { senderID: 'Your_Project_ID' },
           ios: { alert: 'true', badge: 'true', sound: 'true' },
           wns: {}
       });
    
     // Handle the registration event.
     pushRegistration.on('registration', function (data) {
       // Get the native platform of the device.
       var platform = device.platform;
       // Get the handle returned during registration.
       var handle = data.registrationId;
       // Set the device-specific message template.
       if (platform == 'android' || platform == 'Android') {
           // Register for GCM notifications.
           client.push.register('gcm', handle, {
               mytemplate: { body: { data: { message: "{$(messageParam)}" } } }
           });
       } else if (device.platform === 'iOS') {
           // Register for notifications.            
           client.push.register('apns', handle, {
               mytemplate: { body: { aps: { alert: "{$(messageParam)}" } } }
           });
       } else if (device.platform === 'windows') {
           // Register for WNS notifications.
           client.push.register('wns', handle, {
               myTemplate: {
                   body: '<toast><visual><binding template="ToastText01"><text id="1">$(messageParam)</text></binding></visual></toast>',
                   headers: { 'X-WNS-Type': 'wns/toast' } }
           });
       }
     });
    
     pushRegistration.on('notification', function (data, d2) {
       alert('Push Received: ' + data.message);
     });
    
     pushRegistration.on('error', handleError);
     }
    
  3. (Android) In the above code, replace Your_Project_ID with the numeric project ID for your app from the Google Developer Console.

(Optional) Configure and run the app on Android

Complete this section to enable push notifications for Android.

Enable Firebase Cloud Messaging

Since we are targeting the Google Android platform initially, you must enable Firebase Cloud Messaging. Similarly, if you were targeting Microsoft Windows devices, you would enable WNS support.
  1. Log in to the Firebase console. Create a new Firebase project if you don't already have one.
  2. After your project is created click Add Firebase to your Android app and follow the instructions provided.
  3. In the Firebase Console, click the cog for your project and then click Project Settings.
  4. Click the Cloud Messaging tab in your project settings and copy the value of the Server key and Sender ID. These values will be used later to configure the notification hub Access Policy and your notification handler in the app.

Configure the Mobile App backend to send push requests using FCM

  1. In the Azure portal, click Browse All > App Services > your Mobile App backend. Under Settings, click on App Service Push, then click your notification hub name.
  2. Go to Google (GCM), enter the FCM server key you obtained from the Firebase console, then click Save.
Your service is now configured to work with Firebase Cloud Messaging!

Configure your Cordova app for Android

In your Cordova app, open config.xml and replace Your_Project_ID with the numeric project ID for your app from the Google Developer Console.
Copy
 
    <plugin name="phonegap-plugin-push" version="1.7.1" src="https://github.com/phonegap/phonegap-plugin-push.git">
        <variable name="SENDER_ID" value="Your_Project_ID" />
    </plugin>
Open index.js and update the code to use your numeric project ID.
Copy
 
    pushRegistration = PushNotification.init({
        android: { senderID: 'Your_Project_ID' },
        ios: { alert: 'true', badge: 'true', sound: 'true' },
        wns: {}
    });

Configure your Android device for USB debugging

Before you can deploy your application to your Android Device, you need to enable USB Debugging. Perform the following steps on your Android phone:
  1. Go to Settings > About phone, then tap the Build number until developer mode is enabled (about 7 times).
  2. Back in Settings > Developer Options enable USB debugging, then connect your Android phone to your development PC with a USB Cable.
We tested this using a Google Nexus 5X device running Android 6.0 (Marshmallow). However, the techniques are common across any modern Android release.

Install Google Play Services

The push plugin relies on Android Google Play Services for push notifications.
  1. In Visual Studio, click Tools > Android > Android SDK Manager, expand the Extras folder and check the box to make sure that each of the following SDKs is installed.
    • Android 2.3 or higher
    • Google Repository revision 27 or higher
    • Google Play Services 9.0.2 or higher
  2. Click on Install Packages and wait for the installation to complete.
The current required libraries are listed in the phonegap-plugin-push installation documentation.

Test push notifications in the app on Android

You can now test push notifications by running the app and inserting items in the TodoItem table. You can do this from the same device or from a second device, as long as you are using the same backend. Test your Cordova app on the Android platform in one of the following ways:
  • On a physical device:
    Attach your Android device to your development computer with a USB cable. Instead of Google Android Emulator, select Device. Visual Studio will deploy the application to the device and run it. You can then interact with the application on the device.
    Improve your development experience. Screen sharing applications such as Mobizen can assist you in developing an Android application by projecting your Android screen on to a web browser on your PC.
  • On an Android emulator:
    There are additional configuration steps required when running on an emulator.
    Make sure that you are deploying to or debugging on a virtual device that has Google APIs set as the target, as shown below in the Android Virtual Device (AVD) manager.
    If you want to use a faster x86 emulator, you install the HAXM driver and configure the emulator use it.
    Add a Google account to the Android device by clicking Apps > Settings > Add account, then follow the prompts to add an existing Google account to the device (we recommend using an existing account rather than creating a new one).
    Run the todolist app as before and insert a new todo item. This time, a notification icon is displayed in the notification area. You can open the notification drawer to view the full text of the notification.

(Optional) Configure and run on iOS

This section is for running the Cordova project on iOS devices. You can skip this section if you are not working with iOS devices.

Install and run the iOS remotebuild agent on a Mac or cloud service

Before you can run a Cordova app on iOS using Visual Studio, go through the steps in the iOS Setup Guide to install and run the remotebuild agent.
Make sure you can build the app for iOS. The steps in the setup guide are required to build for iOS from Visual Studio. If you do not have a Mac, you can build for iOS using the remotebuild agent on a service like MacInCloud. For more info, see Run your iOS app in the cloud.

Note

XCode 7 or greater is required to use the push plugin on iOS.

Find the ID to use as your App ID

Before you register your app for push notifications, open config.xml in your Cordova app, find the id attribute value in the widget element, and copy it for later use. In the following XML, the ID is io.cordova.myapp7777777.
Copy
 
    <widget defaultlocale="en-US" id="io.cordova.myapp7777777"
      version="1.0.0" windows-packageVersion="1.1.0.0" xmlns="http://www.w3.org/ns/widgets"
        xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:vs="http://schemas.microsoft.com/appx/2014/htmlapps">
Later, use this identifier when you create an App ID on Apple's developer portal. (If you create a different App ID on the developer portal and want to use that, you will need to take a few extra steps later in this tutorial to change this ID in config.xml. The ID in the widget element must match the App ID on the developer portal.)

Register the app for push notifications on Apple's developer portal

Configure Azure to send push notifications

  1. On your Mac, launch Keychain Access. Open My Certificates under Category on the left navigationn bar. Find the SSL certificate you downloaded in the previous section and disclose its contents. Select only the certificate (do not select the private key), and export it.
  2. In the Azure portal, click Browse All > App Services > your Mobile App backend. Under Settings, click on App Service Push, then click your notification hub name. Go to Apple Push Notification Services > Upload Certificate. Upload the .p12 file, selecting the correct Mode (depending on whether your client SSL certificate from earlier is Production or Sandbox). Save any changes.
Your service is now configured to work with push notifications on iOS!

Verify that your App ID matches your Cordova app

If the App ID you created in your Apple Developer Account already matches the ID of the widget element in config.xml, you can skip this step. However, if the IDs don't match, take the following steps:
  1. Delete the platforms folder from your project.
  2. Delete the plugins folder from your project.
  3. Delete the node_modules folder from your project.
  4. Update the id attribute of the widget element in config.xml to use the App ID that you created in your Apple Developer Account.
  5. Rebuild your project.

Test push notifications in your iOS app

  1. In Visual Studio, make sure that iOS is selected as the deployment target, and then choose Device to run on your connected iOS device.
    You can run on an iOS device connected to your PC using iTunes. The iOS Simulator does not support push notifications.
  2. Press the Run button or F5 in Visual Studio to build the project and start the app in an iOS device, then click OKto accept push notifications.

Note

  1. 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 a task, and then click the plus (+) icon.
  3. Verify that a notification is received, then click OK to dismiss the notification.

(Optional) Configure and run on Windows

This section is for running the Apache Cordova app project on Windows 10 devices (the PhoneGap push plugin is supported on Windows 10). You can skip this section if you are not working with Windows devices.

Register your Windows app for push notifications with WNS

To use the Store options in Visual Studio, select a Windows target from the Solution Platforms list, like Windows-x64or Windows-x86 (avoid Windows-AnyCPU for push notifications).
  1. In Visual Studio Solution Explorer, right-click the Windows Store app project, click Store > Associate App with the Store....
    Associate app with Windows Store
  2. In the wizard, click Next, sign in with your Microsoft account, type a name for your app in Reserve a new app name, then click Reserve.
  3. After the app registration is successfully created, select the new app name, click Next, and then click Associate. This adds the required Windows Store registration information to the application manifest.
  4. Repeat steps 1 and 3 for the Windows Phone Store app project using the same registration you previously created for the Windows Store app.
  5. Navigate to the Windows Dev Center, sign-in with your Microsoft account, click the new app registration in My apps, then expand Services > Push notifications.
  6. In the Push notifications page, click Live Services site under Windows Push Notification Services (WNS) and Microsoft Azure Mobile Apps, and make a note of the values of the Package SID and the current value in Application Secret.
    App setting in the developer center

Important

  1. The application secret and package SID are important security credentials. Do not share these values with anyone or distribute them with your app.

Configure the notification hub for WNS

  1. In the Azure portal, click Browse All > App Services > your Mobile App backend. Under Settings, click on App Service Push, then click your notification hub name.
  2. Go to Windows (WNS), enter the Security key (client secret) and Package SID that you obtained from the Live Services site, then click Save.
    Set the WNS key in the portal
Your backend is now configured to use WNS to send push notifications.

Configure your Cordova app to support Windows push notifications

Open the configuration designer (right-click on config.xml and select View Designer), select the Windows tab, and choose Windows 10 under Windows Target Version.

Note

If you are using a Cordova version prior to Cordova 5.1.1 (6.1.1 recommended), you must also set the Toast Capable flag to true in config.xml.
To support push notifications in your default (debug) builds, open build.json file. Copy the "release" configuration to your debug configuration.
Copy
 
    "windows": {
        "release": {
            "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
            "publisherId": "CN=yourpublisherID"
        }
    }
After the update, the preceding code should look like this.
Copy
 
"windows": {
    "release": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
        },
    "debug": {
        "packageCertificateKeyFile": "res\\native\\windows\\CordovaApp.pfx",
        "publisherId": "CN=yourpublisherID"
        }
    }
Build the app and verify that you have no errors. You client app should now register for the notifications from the Mobile App backend. Repeat this section for every Windows project in your solution.

Test push notifications in your Windows app

In Visual Studio, make sure that a Windows platform is selected as the deployment target, such as Windows-x64 or Windows-x86. To run the app on a Windows 10 PC hosting Visual Studio, choose Local Machine.
Press the Run button to build the project and start the app.
In the app, type a name for a new todoitem, and then click the plus (+) icon to add it.
Verify that a notification is received when the item is added.

Next Steps

Learn how to use the SDKs.

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...