I am building a mobile application for both android/Ios,For android,require a push notification using parse to deliver my message and to get my request. I got the device token for my android device and i can list my recipients but if i click on send button my message is not delivered.Here is my code that i have
var uuid=Ti.Platform.createUUID();
var deviceToken;
var CloudPush = require('ti.cloudpush');
//fetch device token
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
//alert('Device Token: ' + deviceToken);
Ti.API.info('Device Token: ' + e.deviceToken);
loginDefault();
/////////parse start///
var c = Titanium.Network.createHTTPClient();
c.setTimeout(25000);
c.onload = function(e) {
Ti.API.info("onload");
svar = JSON.parse(this.responseText);
Ti.API.info(svar);
Ti.API.info('params'+this.responseText);
};
c.onerror = function(e) {
Ti.API.info("on error");
alert(e);
};
c.open('POST', 'https://api.parse.com/1/installations');
c.setRequestHeader('X-Parse-Application-Id', 'bopIfF9m4JpkAxww9syYvLHVaCmE2go9WW7uHS1K');
c.setRequestHeader('X-Parse-REST-API-Key', 'NZLlV86V8ruxq5GdXRi2NrepQXhyiSmmoDHeZasH');
c.setRequestHeader('Content-Type', "application/json; charset=utf-8");
var params = {
"deviceType": "android",
"deviceToken": deviceToken,
"installationId":uuid,
"pushType":"gcm",
};
Ti.API.info('value is'+params);
c.send(JSON.stringify(params));
///parse end/////
},
error : function deviceTokenError(e) {
// alert('Failed to register for push! ' + e.error);
}
});
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
var Cloud = require('ti.cloud');
Cloud.debug = true;
function loginDefault(e) {
//Create a Default User in Cloud Console, and login with same credential
Cloud.Users.login({
login : 'push1',
password : '12345'
},
function(e) {
if (e.success) {
// alert("Login success");
defaultSubscribe();
} else {
// alert('Login error: ' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function defaultSubscribe() {
Cloud.PushNotifications.subscribe({
channel : 'alert',//'alert' is channel name
device_token : deviceToken,
type : 'gcm' //here i am using gcm, it is recomended one
}, function(e) {
if (e.success) {
// alert('Subscribed for Push Notification!');
} else {
//alert('Subscrib error:' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
CloudPush.addEventListener('callback', function(evt) {
// alert(evt.payload);
// alert("ggg");
});
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
Ti.API.info('#### Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
Ti.API.info('#### Tray Click Focused App (app was already running)');
});
Change
c.setRequestHeader('Content-Type', "application/json; charset=utf-8");
to
c.setRequestHeader('Content-Type', "application/json");
Related
I try to create Cordova mobile app based on angularjs following this tutorial: https://mobilefirstplatform.ibmcloud.com/blog/2016/08/11/best-practices-for-building-angularjs-apps-with-mobilefirst-foundation-8.0/
and LTPA Based Security Check login flow (in Mobilefirst 8.0) based on sample from: https://github.com/mfpdev/ldap-and-ltpa-sample
Mobile app is using angular. Authorisation implementation:
app.factory('Auth', function ($rootScope) {
var securityCheckName = 'LTPA',
_$scope = null,
challengeHandler = null,
URL = '',
challengeHandler = WL.Client.createSecurityCheckChallengeHandler(securityCheckName);
challengeHandler.securityCheckName = securityCheckName;
WLAuthorizationManager.login(securityCheckName, {'username': '', 'password': ''});
challengeHandler.handleChallenge = function (challenge) {
if (challenge && challenge.loginURL) {
URL = challenge.loginURL;
}
};
challengeHandler.handleSuccess = function (data) {
// code
};
challengeHandler.handleFailure = function (error) {
// code
};
return {
login: function ($scope, username, password) {
_$scope = $scope;
var request = new WLResourceRequest(URL, WLResourceRequest.POST);
request.send("j_username=" + username + "&j_password=" + password + "&action=Login").then(
function(response) {
challengeHandler.submitChallengeAnswer({});
},
function(error) {
// on error
});
}
};
});
This seems to work only on iOS. On Android handleSuccess function is not invoked.
As in the past, there was a problem with sending cookies on Android devices (with older MF versions) so I tried workaround in login function, that the hidden InAppBrowser was opened with logon form, then a user login process was made and once token was received, it was set via cordova-cookie-master-plugin and submitChallengeAnswer was invoked:
login: function ($scope, username, password) {
_$scope = $scope;
var request = new WLResourceRequest(URL, WLResourceRequest.POST);
request.send("j_username=" + username + "&j_password=" + password + "&action=Login").then(
function(response) {
if (device.platform == "iOS") {
challengeHandler.submitChallengeAnswer({});
} else {
iab = cordova.InAppBrowser.open(URL, "_blank", "hidden=yes");
iab.addEventListener('loadstop', function(event){
iab.executeScript({code:
'var field1 = document.getElementsByTagName("input")[0];' +
'var field2 = document.getElementsByTagName("input")[1];' +
'field1.setAttribute("value", "' + username + '");' +
'field2.setAttribute("value", "' + password + '");' +
'document.forms[0].submit();'
}, function(){
// on error
});
try {
cookieMaster.getCookieValue(URL, 'LtpaToken2', function(data) {
WL.Client.setCookie({
"name" : "LtpaToken2",
"value" : data.cookieValue,
"domain" : ".example.com",
"path" : "/",
"expires" : "Thu, 18 Dec 2999 12:00:00 UTC"
}).then(function() {
challengeHandler.submitChallengeAnswer({});
}).fail(function(err) {
// on error
});
}, function(error) {
// on error
});
} catch(err) {
// on error
}
});
iab.addEventListener('exit', function(){
iab.removeEventListener('loadstop', function() { /* on success */ });
});
}
},
function(error) {
// on error
});
}
This solution also not working for me. I've expect that after challengeHandler.submitChallengeAnswer() was fired, the handleSuccess will be invoked, but it is not happened. handleChallenge is invoked instead.
I have received push notification using FCM plugin. when i m clicking on notifiation, app splash screen was open but i but open another screen. how can i do it? please help.
app.js
.run(function ($ionicPlatform, $rootScope, $state) {
$ionicPlatform.ready(function() {
if(window.cordova) {
FCMPlugin.onNotification(
function(data){
$rootScope.notificationData = data;
$rootScope.reciveMessage(data);
$state.reload();
if(data.wasTapped){
// $state.go('message', {id:data.pageId});
// $location.path('app/userList');
console.log('onNotification tapped true');
} else {
console.log("xxxxxxxxxxxx"+data.message);
}
},
function(msg){
// alert("asdf"+msg)
console.log('onNotification callback successfully registered: ' + msg);
FCMPlugin.getToken(
function(token){
//alert(token);
window.localStorage.setItem("deviceId",token)
},
function(err){
console.log('error retrieving token: ' + err);
}
)
},
function(err){
// alert("fjkjg"+err)
console.log('Error registering onNotification callback: ' + err);
}
);
}
});
})
I need to make a push notification listener, My code for this is below and it runs perfect till the subscription and the dashboard confirms it is subscribed successfully, but the problem occurs with the receiver.
Alloy.Globals.ServiceAddress = "my service address";
Ti.API.info("1");
var CloudPush = require('ti.cloudpush');
var Cloud = require("ti.cloud");
var deviceToken = null;
loginUser(); // flow starts from here
function loginUser() {
Cloud.Users.login({
login: 'User',
password: 'Password'
}, function(e) {
if (e.success) {
var user = e.users[0];
// alert("Loggin successfully");
getDeviceToken();
} else {
alert("Error2*** :" + e.message);
//Ti.API.info('error ')
}
});
}
function getDeviceToken() {
if (Ti.Platform.Android) {
CloudPush.debug = true;
CloudPush.focusAppOnPush = false;
CloudPush.enabled = true;
CloudPush.showAppOnTrayClick = true;
CloudPush.showTrayNotification = true;
CloudPush.singleCallback = true;
CloudPush.singleCallback = true;
CloudPush.retrieveDeviceToken({
success: deviceTokenSuccess,
error: deviceTokenError
});
}
}
// Enable push notifications for this device
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
alert(e.deviceToken);
subscribeToChannel(deviceToken);
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
// Process incoming push notifications
function subscribeToChannel(deviceToken) {
// 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: 'Vision', //'You_App',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function(e) {
if (e.success) {
alert('Subscribed');
SendNotification(deviceToken);
} else {
// indicator.visible = false;
alert('Subscribe Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function SendNotification(to_deviceToken) {
alert('sendnot');
Cloud.PushNotifications.notifyTokens({
channel: 'My Cannel',
to_tokens: to_deviceToken,
payload: 'Welcome to push notifications'
}, function(e) {
if (e.success) {
alert('Success Send');
} else {
alert('Send Error:\n' +
((e.error && e.message) || JSON.stringify(e)));
}
});
}
When I add event-listener to push notifications it doesn't even fire up however, the client is saying it is connected.
<!-- language: lang-js -->
CloudPush.addEventListener('callback', function (evt) {
alert('rec');
alert("Notification received: " + evt.payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function (evt) {
Ti.API.info('Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function (evt) {
Ti.API.info('Tray Click Focused App (app was already running)');
});
PS. I have searched and already read related threads Like this one
I am attaching the log to make it clarify that subscription and notification send is working properly
Push notification Log
and
Connected Clients
Solved
I was compiling with titanium api level 4.1.1.v20151203143424 with CloudPush module version 3.2.1
I migrated to titanium 6.0.0.v20160202173231 with cloudpush module version 3.4.1
and all set see in this pic
Registration id is giving but event is not triggered. I don't understand why?
Please Help me. I did not understand where wrong?
// Cloud module and Cloud module use
Titanium.UI.setBackgroundColor('#000');
var win = Ti.UI.createWindow({
backgroundColor : '#ccc',
title : 'Android Cloud Push Notification'
});
//CloudPush modules variables
var CloudPush = require('ti.cloudpush');
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotification = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
//Device Token variables
var deviceToken;
var Cloud = require('ti.cloud');
Cloud.debug = true;
//create button
var submit = Ti.UI.createButton({
title : 'Register For Push Notification',
color : '#000',
height : 53,
width : 200,
top : 100,
});
//add button on win scene
win.add(submit);
//CloudPush retrieveDeviceToken function
submit.addEventListener('click', function(e) {
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
alert('======= Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
loginDefault();
},
error : function deviceTokenError(e) {
alert('======= Failed to register for push! ' + e.error);
}
});
});
//Cloud login
function loginDefault(e) {
// At first you need to create an user from the application dashboard
// Then login that email and password
Cloud.Users.login({
login : '===',
password : '==='
}, function(e) {
if (e.success) {
alert("========login success");
defaultSubscribe();
} else {
alert('Error: ' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function defaultSubscribe() {
Cloud.PushNotifications.subscribe({
channel : 'alert',
device_token : deviceToken,
type : 'android'
}, function(e) {
if (e.success) {
alert('====== Subscribed for Push Notification!');
} else {
alert('Error:' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
//Doesnt Work this events
CloudPush.addEventListener('callback', function(evt) {
console.log(evt);
console.log(evt.payload);
});
//Doesnt Work this events
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
console.log('Tray Click Launched App (app was not running)');
//alert('Tray Click Launched App (app was not running');
});
//Doesnt Work trayClickFocusedApp events
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
console.log('Tray Click Focused App (app was already running)');
//alert('Tray Click Focused App (app was already running)');
});
win.open();
I added push notification "events" but is not working.
I dont understand. Error can not be given and Log in is not working.
please help me. Thanks
my gcm module
var gcm = require("nl.vanvianen.android.gcm");
var CloudPush = require('ti.cloudpush');
/* If the app is started or resumed act on pending data saved when the notification was received */
var lastData = gcm.getLastData();
if (lastData) {
Ti.API.info("Last notification received " + JSON.stringify(lastData));
gcm.clearLastData();
}
gcm.registerPush({
senderId : '480608162759',
notificationSettings : {
sound : 'mysound.mp3',
smallIcon : 'notification_icon.png',
largeIcon : 'appicon.png',
vibrate : true
},
success : function(event) {
Ti.API.info("Push registration success: " + JSON.stringify(event));
},
error : function(event) {
Ti.API.info("Push registration error = " + JSON.stringify(event));
alert(event.error);
},
callback : function(event) {
Ti.API.info("Push callback = " + JSON.stringify(event));
var dialog = Ti.UI.createAlertDialog({
title : 'Push received',
message : JSON.stringify(event.data)
// buttonNames: ['View'],
// cancel: 1
});
dialog.addEventListener("click", function(event) {
dialog.hide();
if (event.index == 0) {
/* Do stuff to view the notification */
}
});
dialog.show();
},
});
//Dont work eventlistener
CloudPush.addEventListener('callback', function(evt) {
console.log("Notification received: " + evt.payload);
});