Skip to content

Instantly share code, notes, and snippets.

@orthodoc
Forked from jason-engage/gist:e072cc300fd789e8841e
Last active September 21, 2015 08:09
Show Gist options
  • Save orthodoc/5f0060ec7eed6bda9ce2 to your computer and use it in GitHub Desktop.
Save orthodoc/5f0060ec7eed6bda9ce2 to your computer and use it in GitHub Desktop.
Ionic Register Push Function Example with Payload and ionicPopup for Android and IOS
//Here is the curl commands I use to test - make sure you update the CAPSVARS. You can add an item ID Payload or not.
//For example if your app displays items, it can navigate to a specific item.
//If you want to add more state names, instead of only going to specific items:
//add another payload property called 'stateName'
//create a goState() function to accept a stateName as a parameter
//and modify the registerPush() to find the stateName property and pass into your goState().
//Android
curl -u YOURAPIKEY: -H "Content-Type: application/json" -H "X-Ionic-Application-Id: APPID" https://push.ionic.io/api/v1/push -d '{"tokens":["ANDROIDTOKEN"],"notification":{"alert":"I come from planet Ion.", "android":{"title":"This is a title2", "payload":{"sound":"notification.mp3","itemId":"7TF00hJI78Y"}}}}'
//IOS
curl -u YOURAPIKEY: -H "Content-Type: application/json" -H "X-Ionic-Application-Id: APPID" https://push.ionic.io/api/v1/push -d '{"tokens":["IOSTOKEN"],"notification":{"alert":"I come from planet Ion.","ios":{"sound":"notification.mp3", "badge":1, "payload":{ "itemId":"7TF00hJI78Y"}}}}'
//I recommend the Native-Audio Plugin to play notification sounds.
//Not plugin-media (For some reason I could never get it working right on ios, and the app sounds stop my bg music player!)
//Here is the goItem function:
$rootScope.goItem = function(index, playSoundBool) {
console.log('Go Item ' + index);
$state.go('item', {
"itemId": index
});
$rootScope.currentPage = "Item";
$rootScope.playSound(playSoundBool);
}
//Just to be sure, something like this should be in your app.js:
.state('item', {
url: '/item/:itemId',
views: {
'root': {
templateUrl: 'templates/item.html',
controller: 'ItemCtrl'
}
}
})
//Here is the PushCode - Keep it as a function and call it like so
//$ionicUser.identify(...).then( registerPush() );
//There are some things in here that will be missing from your project/injections/functions.
//Just read thru it and make your mods.
function registerPush() {
//Only allow on mobile devices
if (window.cordova) {
$ionicPush.register({
canShowAlert: false, //Can pushes show an alert on your screen? Debug Only
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification, event) {
// Handle new push notifications here
console.log('Ionic Push Event Received!', notification);
if (ionic.Platform.isAndroid()) {
handleAndroid(notification);
} else if (ionic.Platform.isIOS()) {
handleIOS(notification);
}
//Android and IOS alert popup
function showAlertPopup(notificationString, notificationItem) {
if (notificationItem && notificationString) {
showingPushPopup = $ionicPopup.confirm({
title: notificationString,
okText: 'View it',
cancelText: 'Later',
cancelType: 'button-clear',
okType: 'button-stable'
}).then(function(response) {
if (response) {
$rootScope.goItem(notificationItem);
}
} else {
//clicked cancel
}
});
} else if (notificationString) {
$ionicPopup.alert({
title: notificationString,
okType: 'button-stable'
}).then(function() {
//nothing
});
}
}
// Android Notification Received Handler
function handleAndroid(notification) {
// You could add code for when app is in foreground or not, or coming from coldstart here too
console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart);
var payload = {};
//Check for Payload
if (notification.payload && notification.payload.payload) {
payload = notification.payload.payload;
}
if (!notification.coldstart) {
if (notification.event == "message") {
if (data.user.enableTabSound && payload.sound) {
// Using NATIVEAUDIO PLUGIN
$rootScope.playNotificationSound();
}
//Show popup asking to go to item
if (payload.itemId) {
showAlertPopup(notification.message, payload.itemId);
} else {
showAlertPopup(notification.message);
}
// There is no need to use cordova dialogs!
//$cordovaDialogs.alert(notification.message, "Push Notification Received");
} else if (notification.event == "error") {
//ErrorService.sendError({
// message: notification.msg,
// controller: "LoginService",
// event: "Android Push Notification Error"
//});
}
} else if (notification.coldstart && payload.itemId) {
//Go straight to the item page
$rootScope.goItem(payload.itemId);
}
}
// IOS Notification Received Handler
function handleIOS(notification) {
// The app was already open but we'll still show the alert and sound the tone received this way. If you didn't check
// for foreground here it would make a sound twice, once when received in background and upon opening it from clicking
// the notification when this code runs (weird).
if (notification.foreground == "1") {
// Play custom audio if a sound specified. Using NATIVEAUDIO PLUGIN
if (notification.sound) {
$rootScope.playNotificationSound();
}
if (notification.body) {
//Send to item
if (notification.itemId) {
showAlertPopup(notification.body, notification.itemId);
} else {
showAlertPopup(notification.body);
}
}
// Updating the badge from the foreground is unnecessary
// if (notification.badge) {
// $cordovaPush.setBadgeNumber(notification.badge).then(function(result) {
// console.log("Set badge success " + result)
// }, function(err) {
// console.log("Set badge error " + err)
// });
// }
}
// Otherwise it was received in the background and reopened from the push notification.
//Badge is automatically cleared in this case.
else if (!notification.foreground && notification.itemId) {
$rootScope.goItem(notification.itemId);
}
}
return true;
}
}).then(function(result) {
console.log('$ionicPush.register result: ' + result)
});
$rootScope.$on('$cordovaPush:tokenReceived', function(event, data) {
console.log("Got token", data.token, data.platform);
//If the new token is different than the old one
if (!$rootScope.user.lastPushToken || $rootScope.user.lastPushToken != data.token) {
//Update Local
$rootScope.user.lastPushToken = data.token;
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment