Skip to content

Instantly share code, notes, and snippets.

@mulhoon
Created November 14, 2016 16:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mulhoon/da622cd1f6645468fbf752b69c5e66c2 to your computer and use it in GitHub Desktop.
Save mulhoon/da622cd1f6645468fbf752b69c5e66c2 to your computer and use it in GitHub Desktop.
How to add push notification to a Cordova project - the easy and reliable way.

Push Notifications for cordova.

Use One Signal to add push notifications. There's no need to do anything on the Apple Member Center.

Set up One Signal

  1. Use this to download a .p12 file
  2. Add a new app using the same .p12 for developer and production
  3. Note your App ID and REST API Key from App Settings > Keys & IDs

In your app

  1. Add the plugin cordova plugin add onesignal-cordova-plugin

  2. Add this script and call... App.push.init(appID, callback)

callback recieves a user id (UID). Store it on a server if you want to push directly to this user.

Send a notification

From Node

See this Gist

From your terminal...
curl -X POST -H "Authorization: Basic [---REST API Key---]" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
  "app_id": [---App ID---],
  "contents": {"en": "Hello there!"},
  "include_player_ids": [ [---UID---] ]
}' "https://onesignal.com/api/v1/notifications"
From Javascript
var appID = [---App ID---];
var restKey = [---REST API Key---];
var user = [---UID---];
var message = "Hello World";

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://onesignal.com/api/v1/notifications",
  "method": "POST",
  "headers": {
    "authorization": "Basic "+restKey,
    "content-type": "application/json",
    "cache-control": "no-cache",
  },
  "processData": false,
  "data": "{\n  \"app_id\": \""+appID+"\",\n  \"contents\": {\"en\": \""+message+"\"},\n  \"include_player_ids\": [\""+user+"\"]\n}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
From anywhere

More at https://documentation.onesignal.com/docs/server-api-overview

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment