phonegap push notification works on android but not on ios - ios

As the title says Push notification works fine on android but on IOS it does not. push.on(registration...) is never called. I have made sure that provisional profiles are valid for both development and distribution. I am using firebase for cloud messaging.I am looking for any sort of guidance on how to fix this.
Here is the console out put:
2017-03-23 16:15:49.741405 [342:34586] Push Plugin register called
2017-03-23 16:15:49.741515 [342:34586] PushPlugin.register: setting badge to false
2017-03-23 16:15:49.741559 [342:34586] PushPlugin.register: clear badge is set to 0
2017-03-23 16:15:49.752879 [342:33926] Push Plugin register success: <######## ######## ######## ######## ######## ######## ######## ########>
.
document.addEventListener("deviceready", function() {
var push = PushNotification.init({
android: {
senderID: "############",
forceShow: true
},
ios: {
sound: true,
alert: true,
badge: true
}
});
push.on('registration', function(data) {
console.log('GCM: ' + data.registrationId);
$rootScope.pushRegStatus = true;
$rootScope.registerPushOnServer(data.registrationId);
});
push.on('notification', function(data) {
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
// console.log('notification' + data.toString());
// App started by clicking on push notification ..
// if(data.additionalData.coldstart === false || data.additionalData.coldstart === true) {
// $location.path('/pushLog/' + data.additionalData.push_log_id);
// }
// Got notification while app is in foreground ..
if(data.additionalData.foreground) {
//$rootScope.alert(data.title, data.message);
} else {
$rootScope.alert(data.title, data.message);
// $location.path('/pushLog/' + data.additionalData.push_log_id);
$rootScope.openPushLogFromNotification = true;
// setTimeout(function() {
// $rootScope.openPushLogFromNotification = false;
// }, 3000);
$location.path('/pushLog');
}
});
push.on('error', function(e) {
// e.message
console.log(e);
});
}, false);

I fixed it by skiping firebase all together and going straight to APNS

Related

Admob plugin for ionic ios

I am working in an project with both platforms like android and ios, i have to implement banner ads in my project. I have tried various plugin to implement the banner ads.
I have tried the below link for android and ios, it working well with android but after adding this plugin my app shows error,
https://www.codeproject.com/Articles/1005149/Adding-AdMob-to-Ionic-Framework-Application-Step-B
plugin name - cordova-plugin-admob
After adding the plugin, i have use the command 'ionic build ios', which returns - Error code 65 for command: xcodebuild with args: -xcconfig,
Don't know the exact reason of this issue.
Atlast I have findout the solution to load Ads in ionic app,
Please add the plugin
cordova plugin add cordova-plugin-admobpro
Add the below code in your html page,
//Script tag to load jquery1.9.js-
<script type="text/javascript" src="jquery-1.9.js"></script>
<script>
var admobid = {};
if( /(android)/i.test(navigator.userAgent) ) {
admobid = { // for Android
banner: 'ca-app-pub-6869992474017983/9375997553',
interstitial: 'ca-app-pub-6869992474017983/1657046752'
};} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
admobid = { // for iOS
banner: 'ca-app-pub-6869992474017983/4806197152',
interstitial: 'ca-app-pub-6869992474017983/7563979554'
};} else {
admobid = { // for Windows Phone
banner: 'ca-app-pub-6869992474017983/8878394753',
interstitial: 'ca-app-pub-6869992474017983/1355127956'
};}function createSelectedBanner(){
//alert("banner");
if(AdMob) AdMob.createBanner({
adId: admobid.banner,
overlap: $('#overlap').is(':checked'),
offsetTopBar: $('#offsetTopBar').is(':checked'),
adSize: 'BANNER',
position: AdMob.AD_POSITION.BOTTOM_CENTER,
});}function showBannerAtPosition(){
if(AdMob) AdMob.showBanner( $('#adPosition').val() );}function onDeviceReady() {
if (! AdMob) {
//alert( 'admob plugin not ready' );
return;
}
initAd();
// display a banner at startup
createSelectedBanner();}function initAd(){//alert("init");
AdMob.getAdSettings(function(info){
console.log('adId: ' + info.adId + '\n' + 'adTrackingEnabled: ' + info.adTrackingEnabled);}, function(){
console.log('failed to get user ad settings');
});
AdMob.setOptions({
adSize: 'BANNER',
position: AdMob.AD_POSITION.BOTTOM_CENTER,
isTesting: true, // set to true, to receiving test ad for testing purpose
bgColor: 'black', // color name, or '#RRGGBB'
// autoShow: true // auto show interstitial ad when loaded, set to false if prepare/show
// offsetTopBar: false, // avoid overlapped by status bar, for iOS7+
});
// new events, with variable to differentiate: adNetwork, adType, adEvent
$(document).on('onAdFailLoad', function(e){
// when jquery used, it will hijack the event, so we have to get data from original event
if(typeof e.originalEvent !== 'undefined') e = e.originalEvent;
var data = e.detail || e.data || e;
//alert('error: ' + data.error +', reason: ' + data.reason +', adNetwork:' + data.adNetwork +', adType:' + data.adType +', adEvent:' + data.adEvent); // adType: 'banner', 'interstitial', etc.
});
$(document).on('onAdLoaded', function(e){
});
$(document).on('onAdPresent', function(e){
});
$(document).on('onAdLeaveApp', function(e){
});
$(document).on('onAdDismiss', function(e){
});
$('#btn_create').click(createSelectedBanner);
$('#btn_remove').click(function(){
AdMob.removeBanner();
});
$('#btn_show').click(showBannerAtPosition);
$('#btn_hide').click(function(){
AdMob.hideBanner();
});
// test interstitial ad
$('#btn_prepare').click(function(){
AdMob.prepareInterstitial({
adId:admobid.interstitial,
autoShow: $('#autoshow').is(':checked'),
});
});
$('#btn_showfull').click(function(){
AdMob.showInterstitial();
});
// test case for #256, https://github.com/floatinghotpot/cordova-admob-pro/issues/256
$(document).on('backbutton', function(){
if(window.confirm('Are you sure to quit?')) navigator.app.exitApp();
});$(document).ready(function()
{
//alert("start");
// on mobile device, we must wait the 'deviceready' event fired by cordova
if(/(ipad|iphone|ipod|android|windows phone)/i.test(navigator.userAgent)) {
document.addEventListener('deviceready', onDeviceReady, false);
} else {
onDeviceReady();
}
});
</script>

Appcelerator Ti.Network.registerForPushNotifications events not firing on iOS

I need to implement PushNotification for iOS device.
The error message this when I want to subscribe a channel
Missing fields. Required: device_token and channel
I have apple certificate and all configurations in Appcelerator dashboard.
And when I am running the app on my device app asking to confirm push notification.
I believe the error appears because of Ti.Network.registerForPushNotifications events not firing.
Here is my code.
var Cloud = require("ti.cloud");
login();
function login() {
env = Ti.App.deployType.toLowerCase() === 'production' ? 'production' : 'development',
username = Ti.App.Properties.getString('acs-username-'+env),
password = Ti.App.Properties.getString('acs-password-'+env);
// Places your already created user id credential
Cloud.Users.login({
login : username,
password : password
}, function(e) {
if (e.success) {
var user = e.users[0];
Ti.API.info(' Login Success:\n' + 'id: ' + user.id + '\n' + 'sessionId: ' + Cloud.sessionId + '\n' + 'first name: ' + user.first_name + '\n' + 'last name: ' + user.last_name);
} else {
Ti.API.info('Error:\n' + ((e.error && e.message)));
}
});
}
var deviceToken = null;
// Check if the device is running iOS 8 or later
if (Ti.Platform.name == "iPhone OS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
Ti.Network.registerForPushNotifications({
success : deviceTokenSuccess,
error : deviceTokenError,
callback : receivePush
});
});
Ti.App.iOS.registerUserNotificationSettings({
types : [Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT, Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND, Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE]
});
}
// For iOS 7 and earlier
else {
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types: [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
],
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
}
function receivePush(e) {
//Ti.API.info('Received push: ' + JSON.stringify(e));
}
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
Ti.API.info("eeeeeeee" + e);
//subscribeToChannel();
}
function deviceTokenError(e) {
Ti.API.info('ssssssssFailed to register for push notifications! ' + e.error);
}
function subscribeToChannel () {
// Subscribes the device to the 'news_alerts' channel
// Specify the push type as either 'android' for Android or 'ios' for iOS
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel: 'news_alerts',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function (e) {
if (e.success) {
Ti.API.info('Subscribed');
} else {
Ti.API.info('Error:\n' + ((e.error && e.message)));
}
});
}
function unsubscribeToChannel () {
// Unsubscribes the device from the 'test' channel
Cloud.PushNotifications.unsubscribeToken({
device_token: deviceToken,
channel: 'news_alerts',
}, function (e) {
if (e.success) {
Ti.API.info('Unsubscribed');
} else {
Ti.API.info('Error:\n' + ((e.error && e.message)));
}
});
}
setTimeout(function() {
subscribeToChannel();
}, 6000);
Before making calls to Arrow DB, make sure your deviceTokenSuccessCB is getting fired and since you have indicated that it's not getting fired then you can below steps for it:
Your iOS device settings are ON for your app's notifications.
You are not using LiveView ON mode as it's a known issue here LiveView ON iOS Notification issue

ACS Appcelerator iOS not receiving push

I'm currently trying to make push notification working for dev/production environment through Appcelerator Platform.
I created my push certificates (dev/prod) on apple developer platform, I exported it to .p12 file, and uploaded it on my ArrowDB iOS Push configuration. My Titanium app and my ArrowDB seems correctly linked (good keys for production and developpement).
From my app, I get device token, I get a successfull return from subscribing to notifications, and I can see from Appcelerator that I have one ios device linked.
When I send push notification from Appcelerator ArrowDB platform, I don't receive anything while Appcelerator logs shows a Successful push.
My code for ACS Notification handling :
var Cloud = require('ti.cloud');
var ANDROID = Ti.Platform.name === 'android';
var IOS = !ANDROID && (Ti.Platform.name === 'iPhone OS');
var BLACKBERRY = !ANDROID && !IOS && (Ti.Platform.name === 'blackberry');
Cloud.debug = true; // optional; if you add this line, set it to false for production
var deviceToken = null;
// Check if the device is running iOS 8 or later
if (Ti.Platform.name == "iPhone OS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {
// Remove event listener once registered for push notifications
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
Ti.Network.registerForPushNotifications({
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
});
// Register notification types to use
Ti.App.iOS.registerUserNotificationSettings({
types: [
Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT,
Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND,
Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE
]
});
}
// For iOS 7 and earlier
else {
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types: [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
],
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
}
// Process incoming push notifications
function receivePush(e) {
console.log('Received push: ' + JSON.stringify(e));
alert('Received push: ' + JSON.stringify(e));
}
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
function ACSPush(acsuid, acspwd) {
this.acsuid = acsuid || false;
this.acspwd = acspwd || false;
}
ACSPush.prototype.registerDevice = function(channel_name, onReceive, onLaunched, onFocused, androidOptions, iosOptions, blackberryOptions) {
var that = this,
token = '';
function deviceTokenSuccess(e) {
console.log('Device Token: ' + e.deviceToken);
token = e.deviceToken;
that.token = token;
loginToACS(that.acsuid, that.acspwd, token, channel_name);
}
function deviceTokenError(e) {
console.log('Token Error: ' + e.error);
}
function receivePush(e) {
onReceive(e.data);
console.log("push notification received: " + JSON.stringify(e.data));
}
if (ANDROID) {
var CloudPush = require('ti.cloudpush');
CloudPush.retrieveDeviceToken({
success : deviceTokenSuccess,
error : deviceTokenError
});
CloudPush.focusAppOnPush = androidOptions.focusAppOnPush || false;
CloudPush.showAppOnTrayClick = androidOptions.showAppOnTrayClick || false;
CloudPush.showTrayNotification = androidOptions.showTrayNotification || false;
CloudPush.showTrayNotificationsWhenFocused = androidOptions.showTrayNotificationsWhenFocused || false;
CloudPush.singleCallback = androidOptions.singleCallback || true;
CloudPush.addEventListener('callback', onReceive);
CloudPush.addEventListener('trayClickLaunchedApp', onLaunched);
CloudPush.addEventListener('trayClickFocusedApp', onFocused);
} else if (IOS) {
// Check if the device is running iOS 8 or later
if (parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
function registerForPush() {
Ti.Network.registerForPushNotifications({
success : deviceTokenSuccess,
error : deviceTokenError,
callback : receivePush
});
// Remove event listener once registered for push notifications
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
};
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', registerForPush);
// Register notification types to use
Ti.App.iOS.registerUserNotificationSettings({
types : iosOptions.types,
categories : iosOptions.categories
});
} else {
// For iOS 7 and earlier
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types : iosOptions.types,
success : deviceTokenSuccess,
error : deviceTokenError,
callback : receivePush
});
}
} else if (BLACKBERRY) {
Ti.BlackBerry.createPushService({
appId : blackberryOptions.appId,
ppgUrl : blackberryOptions.ppgUrl,
usePublicPpg : blackberryOptions.usePublicPpg,
launchApplicationOnPush : blackberryOptions.launchApplicationOnPush,
onSessionCreated : function(e) {
console.log('Session Created');
},
onChannelCreated : function(e) {
console.log('Channel Created\nMessage: ' + e.message + '\nToken: ' + e.token);
token = e.token;
that.token = token;
console.log("Device Token: " + token);
loginToACS(that.acsuid, that.acspwd, token, channel_name);
},
onPushReceived : function(e) {
onReceive(e.data);
e.source.removeAllPushes();
},
onConfigError : function(e) {
console.log('ERROR\nTitle: ' + e.errorTitle + +'\nMsg: ' + e.errorMessage);
},
onError : function(e) {
console.log('ERROR\nTitle: ' + e.errorTitle + +'\nMsg: ' + e.errorMessage);
},
onAppOpened : function(e) {
onLaunched(e.data);
e.source.removePush(e.pushId);
}
});
} else {
alert("Push notification not implemented yet into acspushmod for " + Ti.Platform.osname);
}
};
ACSPush.prototype.unsubscribeFromChannel = function(channel_name, token, onSuccess, onFail) {
var that = this;
Cloud.PushNotifications.unsubscribe({
channel : channel_name,
device_token : token
}, function(e) {
if (e.success) {
onSuccess(e);
} else {
onFail(e);
}
});
};
ACSPush.prototype.getToken = function() {
return this.token;
};
function loginToACS(acsuid, acspwd, token, channel_name) {
if (!acsuid && !acspwd) {
console.log("loginToACS -> subscribe as guest");
subscribeForPushNotifications(token, channel_name, true);
return;
}
Cloud.Users.login({
login : acsuid,
password : acspwd
}, function(e) {
if (e.success) {
var user = e.users[0];
console.log("loginToACS -> Status: Successful");
subscribeForPushNotifications(token, channel_name);
} else {
console.log('acsuid = ' + acsuid + " acspwd = " + acspwd);
console.log("loginToACS -> Error :" + e.message);
}
});
};
function subscribeForPushNotifications(token, channel_name, subscribeAsGuest) {
var prams = {
channel : channel_name,
type : IOS ? 'ios' : Ti.Platform.osname, // osname return iphone / ipad on iOS
device_token : token
};
var callBack = function(e) {
if (e.success) {
console.log('subscribeForPushNotifications -> Status: Successful [' + channel_name + ']');
} else {
console.log('subscribeForPushNotifications -> Error ' + token + '(subscribeToServerPush) :\\n' + ((e.error && e.message) || JSON.stringify(e)));
}
};
if (subscribeAsGuest) {
Cloud.PushNotifications.subscribeToken(prams, callBack);
} else {
Cloud.PushNotifications.subscribe(prams, callBack);
}
};
And This code used to work before I change appcelerator account (migrating to my client account).
If you guys have any idea of what am I doing wrong, I will be very thankful.
Thanks a lot !
Environment : Appcelerator studio, Titanium SDK 5.0.0.GA, iphone5S

Titanium Appcelerator unable to send push notification to a specified user

I'm making an app using appcelerator alloy framework which needs push notifications. I'm using push notifications for the first time, so bear with me and help me out here.
I've followed the push notification wiki tutorial here https://wiki.appcelerator.org/display/guides2/Push+Notifications
This is my code here :
var deviceToken = null;
// Check if the device is running iOS 8 or later
if (Ti.Platform.name == "iPhone OS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {
// Remove event listener once registered for push notifications
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
Ti.Network.registerForPushNotifications({
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
});
// Register notification types to use
Ti.App.iOS.registerUserNotificationSettings({
types: [
Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT,
Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND,
Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE
]
});
}
// For iOS 7 and earlier
else {
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types: [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
],
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
}
// Process incoming push notifications
function receivePush(e) {
alert('Received push: ' + JSON.stringify(e));
}
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
// Require the Cloud module
var Cloud = require("ti.cloud");
function subscribeToChannel () {
// Subscribes the device to the 'chats' channel
// Specify the push type as either 'android' for Android or 'ios' for iOS
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel:'test',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function unsubscribeToChannel () {
// Unsubscribes the device from the 'test' channel
Cloud.PushNotifications.unsubscribeToken({
device_token: deviceToken,
channel:'test',
}, function (e) {
if (e.success) {
alert('Unsubscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function loginUser(username, password){
// Log in to Arrow
Cloud.Users.login({
login: username,
password: password
}, function (e) {
if (e.success) {
subscribeToChannel ();
alert('Login successful with device token' + deviceToken);
// Store the authentication details in the local filesystem
Ti.App.Properties.setString('usernameSave',username);
Ti.App.Properties.setString('passwordSave',password);
// user_id = jsonPost.SuccessResult.user_id;
} else {
alert('Error:\n' +
((e.error && e.message) || JSON.stringify(e)));
}
});
}
var savedUserName = Ti.App.Properties.getString('usernameSave','');
var savedPassword = Ti.App.Properties.getString('passwordSave','');
if(savedUserName != ''){
$.userNameField.value = savedUserName;
$.passwordField.value = savedPassword;
}
function login(){
var username = $.userNameField.value;
var password = $.passwordField.value;
loginUser(username, password);
}
The Login() function is called when a button named login is clicked.
I get the Login Successful and Subscribed alerts as expected on login.
Whenever I tried sending a push notification to all the users, it worked. But if I try to send it to a specified user it gives me a failure on the Push Logs in the dashboard.
What am I missing here? Please help me out.
Thanks.
Ok I found the problem that was causing this.
Yeah it was my fault as in the subscription method I'm using token subscription instead of channel subscription. As I'm using the session based method.
Here is the difference, if anyone needs it in future.
Check the second line...
Previous Code
function subscribeToChannel () {
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel:'test',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
New Code
function subscribeToChannel(){
Cloud.PushNotifications.subscribe({
device_token: deviceToken,
channel: 'test',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
Thank you.
Cheers.

Notifications not working with ios8 - Pushwoosh + phonegap

4 apps in apple store and android market created with pushwoosh + phonegap build. Notifications works good on all devices except for new ios8. why? is sometheing changed? I used these 2 files:
Pushnotification.js
(function(cordova) {
function PushNotification() {}
// Call this to register for push notifications and retreive a deviceToken
PushNotification.prototype.registerDevice = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "registerDevice", config ? [config] : []);
};
// Call this to set tags for the device
PushNotification.prototype.setTags = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "setTags", config ? [config] : []);
};
// Call this to send geo location for the device
PushNotification.prototype.sendLocation = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "sendLocation", config ? [config] : []);
};
PushNotification.prototype.onDeviceReady = function() {
cordova.exec(null, null, "PushNotification", "onDeviceReady", []);
};
// Call this to get tags for the device
PushNotification.prototype.getTags = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "getTags", []);
};
//Android Only----
PushNotification.prototype.unregisterDevice = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "unregisterDevice", []);
};
//config params: {msg:"message", seconds:30, userData:"optional"}
PushNotification.prototype.createLocalNotification = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "createLocalNotification", config ? [config] : []);
};
PushNotification.prototype.clearLocalNotification = function() {
cordova.exec(null, null, "PushNotification", "clearLocalNotification", []);
};
//advanced background task to track device position and not drain the battery
PushNotification.prototype.startGeoPushes = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "startGeoPushes", []);
};
PushNotification.prototype.stopGeoPushes = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "stopGeoPushes", []);
};
//sets multi notification mode on
PushNotification.prototype.setMultiNotificationMode = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "setMultiNotificationMode", []);
};
//sets single notification mode
PushNotification.prototype.setSingleNotificationMode = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "setSingleNotificationMode", []);
};
//type: 0 default, 1 no sound, 2 always
PushNotification.prototype.setSoundType = function(type, success, fail) {
cordova.exec(success, fail, "PushNotification", "setSoundType", [type]);
};
//type: 0 default, 1 no vibration, 2 always
PushNotification.prototype.setVibrateType = function(type, success, fail) {
cordova.exec(success, fail, "PushNotification", "setVibrateType", [type]);
};
PushNotification.prototype.setLightScreenOnNotification = function(on, success, fail) {
cordova.exec(success, fail, "PushNotification", "setLightScreenOnNotification", [on]);
};
//set to enable led blinking when notification arrives and display is off
PushNotification.prototype.setEnableLED = function(on, success, fail) {
cordova.exec(success, fail, "PushNotification", "setEnableLED", [on]);
};
//{goal:'name', count:3} (count is optional)
PushNotification.prototype.sendGoalAchieved = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "sendGoalAchieved", config ? [config] : []);
};
//Android End----
//iOS only----
PushNotification.prototype.startLocationTracking = function(backgroundMode, success, fail) {
cordova.exec(success, fail, "PushNotification", "startLocationTracking", backgroundMode ? [{mode : backgroundMode}] : []);
};
PushNotification.prototype.stopLocationTracking = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "stopLocationTracking", []);
};
// Call this to get a detailed status of remoteNotifications
PushNotification.prototype.getRemoteNotificationStatus = function(callback) {
cordova.exec(callback, callback, "PushNotification", "getRemoteNotificationStatus", []);
};
// Call this to set the application icon badge
PushNotification.prototype.setApplicationIconBadgeNumber = function(badgeNumber, callback) {
cordova.exec(callback, callback, "PushNotification", "setApplicationIconBadgeNumber", [{badge: badgeNumber}]);
};
// Call this to clear all notifications from the notification center
PushNotification.prototype.cancelAllLocalNotifications = function(callback) {
cordova.exec(callback, callback, "PushNotification", "cancelAllLocalNotifications", []);
};
//iOS End----
// Event spawned when a notification is received while the application is active
PushNotification.prototype.notificationCallback = function(notification) {
var ev = document.createEvent('HTMLEvents');
ev.notification = notification;
ev.initEvent('push-notification', true, true, arguments);
document.dispatchEvent(ev);
};
cordova.addConstructor(function() {
if(!window.plugins) window.plugins = {};
window.plugins.pushNotification = new PushNotification();
});
})(window.cordova || window.Cordova || window.PhoneGap);
And app.js
function registerPushwooshIOS() {
var pushNotification = window.plugins.pushNotification;
//push notifications handler
document.addEventListener('push-notification', function(event) {
var notification = event.notification;
//navigator.notification.alert(notification.aps.alert);
//to view full push payload
//navigator.notification.alert(JSON.stringify(notification));
//reset badges on icon
pushNotification.setApplicationIconBadgeNumber(0);
});
pushNotification.registerDevice({alert:true, badge:true, sound:true, pw_appid:"69620-5C1D0", appname:"Maxistore"},
function(status) {
var deviceToken = status['deviceToken'];
console.warn('registerDevice: ' + deviceToken);
onPushwooshiOSInitialized(deviceToken);
},
function(status) {
console.warn('failed to register : ' + JSON.stringify(status));
navigator.notification.alert(JSON.stringify(['failed to register ', status]));
});
//reset badges on start
pushNotification.setApplicationIconBadgeNumber(0);
}
function onPushwooshiOSInitialized(pushToken)
{
var pushNotification = window.plugins.pushNotification;
//retrieve the tags for the device
pushNotification.getTags(function(tags) {
console.warn('tags for the device: ' + JSON.stringify(tags));
},
function(error) {
console.warn('get tags error: ' + JSON.stringify(error));
});
//start geo tracking. PWTrackSignificantLocationChanges - Uses GPS in foreground, Cell Triangulation in background.
pushNotification.startLocationTracking('PWTrackSignificantLocationChanges',
function() {
console.warn('Location Tracking Started');
});
}
function registerPushwooshAndroid() {
var pushNotification = window.plugins.pushNotification;
//push notifications handler
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
//dump custom data to the console if it exists
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
//and show alert
//navigator.notification.alert(title);
//stopping geopushes
pushNotification.stopGeoPushes();
});
//projectid: "GOOGLE_PROJECT_ID", appid : "PUSHWOOSH_APP_ID"
pushNotification.registerDevice({ projectid: "863823034249", appid : "69620-5C1D0" },
function(token) {
alert(token);
//callback when pushwoosh is ready
onPushwooshAndroidInitialized(token);
},
function(status) {
alert("failed to register: " + status);
console.warn(JSON.stringify(['failed to register ', status]));
});
}
function onPushwooshAndroidInitialized(pushToken)
{
//output the token to the console
console.warn('push token: ' + pushToken);
var pushNotification = window.plugins.pushNotification;
pushNotification.getTags(function(tags) {
console.warn('tags for the device: ' + JSON.stringify(tags));
},
function(error) {
console.warn('get tags error: ' + JSON.stringify(error));
});
//set multi notificaiton mode
//pushNotification.setMultiNotificationMode();
//pushNotification.setEnableLED(true);
//set single notification mode
//pushNotification.setSingleNotificationMode();
//disable sound and vibration
//pushNotification.setSoundType(1);
//pushNotification.setVibrateType(1);
pushNotification.setLightScreenOnNotification(false);
//goal with count
//pushNotification.sendGoalAchieved({goal:'purchase', count:3});
//goal with no count
//pushNotification.sendGoalAchieved({goal:'registration'});
//setting list tags
//pushNotification.setTags({"MyTag":["hello", "world"]});
//settings tags
pushNotification.setTags({deviceName:"hello", deviceId:10},
function(status) {
console.warn('setTags success');
},
function(status) {
console.warn('setTags failed');
});
function geolocationSuccess(position) {
pushNotification.sendLocation({lat:position.coords.latitude, lon:position.coords.longitude},
function(status) {
console.warn('sendLocation success');
},
function(status) {
console.warn('sendLocation failed');
});
};
// onError Callback receives a PositionError object
//
function geolocationError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function getCurrentPosition() {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
}
//greedy method to get user position every 3 second. works well for demo.
// setInterval(getCurrentPosition, 3000);
//this method just gives the position once
// navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
//this method should track the user position as per Phonegap docs.
// navigator.geolocation.watchPosition(geolocationSuccess, geolocationError, { maximumAge: 3000, enableHighAccuracy: true });
//Pushwoosh Android specific method that cares for the battery
pushNotification.startGeoPushes();
}
function initPushwoosh() {
var pushNotification = window.plugins.pushNotification;
if(device.platform == "Android")
{
registerPushwooshAndroid();
pushNotification.onDeviceReady();
}
if(device.platform == "iPhone" || device.platform == "iOS")
{
registerPushwooshIOS();
pushNotification.onDeviceReady();
}
}
The push notification interface changed in iOS8. If your third-party library hasn't been updated to adapt, push notifications will likely fail.
Background:
Previously, registering for notifications was done with
-[UIApplication registerForRemoteNotificationTypes:]
As of iOS8, it is now done with:
-[UIApplication registerUserNotificationSettings:]
-[UIApplication registerForRemoteNotifications]
Take a look at the pushwoosh post
Due to multiple support requests about iOS 8 we thought it’d be good to also shed some light here in our Blog. Currently, there are two version of Pushwoosh iOS SDK:
iOS 7 SDK – must be compiled with Xcode v.5 – does not support latest features introduced in iOS 8;
iOS 8 SDK – must be compiled with Xcode v.6
So, applications compiled with iOS 7 SDK in Xcode v.5 will continue working properly on devices running iOS 8 due to its compatibility. If you use Pushwoosh iOS 8 SDK, you must compile your app with Xcode v.6.
You can download it here

Resources