I'm having troubles trying to register my GCM regid with ngCordova and $cordovaPush.
I can't manage to retrieve my regid inside my controller to send it to my API via $http:
var gcmToken;
gcmNotificationHandler = function(e) {
if (e.event === "registered") {
gcmToken = e.regid;
console.log(gcmToken);
}
};
var aTonAvis = angular.module('aTonAvis', ['ngCordova']);
aTonAvis.value('serverUrl', "http://atonavis.local/");
aTonAvis.controller('RegisterCtrl', function($scope, $cordovaPush,
$cordovaDevice, $http, serverUrl) {
var gcmConfig = {
"senderID": "00000000000"
};
var iosConfig = {
"badge": "true",
"sound": "true",
"alert": "true",
};
gcmConfig.ecb = "gcmNotificationHandler";
iosConfig.ecb = "iosNotificationHandler";
var configHandler = function() {
if ($cordovaDevice.getPlatform().toLowerCase() ===
'android' || $cordovaDevice.getPlatform() ===
'amazon-fireos') {
return gcmConfig;
} else {
return iosConfig;
}
};
this.registered = false;
document.addEventListener("deviceready", function onDeviceReady() {
$cordovaPush.register(configHandler()).then(function(
result) {
console.log("Inside register " + gcmToken);
var pushToken;
if ($cordovaDevice.getPlatform().toLowerCase() ===
'ios') pushToken = result;
else pushToken = gcmToken;
$http.post(serverUrl + 'api/setdevice', {
token: pushToken,
device: $cordovaDevice.getPlatform(),
version: $cordovaDevice.getVersion(),
model: $cordovaDevice.getModel()
}).success(function(data, status,
headers, config) {
this.registered = true;
});
}, function(err) {
console.log("Registering Error : " + err);
});
});
});
The .then function is fired before the gcmNotificationHandler so my gcmToken is undefined, and here's what I get in my logs :
Inside register : undefined app.js:41
APA91bEzVUk3T1T6WpIsEHOq43hCh_pZeBPjRDPSPxV2j6VjVW-KcUepbmf6snaCiqGvYp3H_XYHIXQdbVtvMF3t-NtoZJaJzV9FkNtUlutuWYs5XPAZ-H1ixQnAyhTO6fAPDMn7Ef5f5HgBR9fgWpmXc0u_xBM4yKvoXCnVXEG18IZV2hvY app.js:6
I don't know what I'm doing wrong here, can anybody help ?
You need to install these two cordova plugins before run the app.
Device cordova plugin: https://github.com/apache/cordova-plugin-device
cordova plugin add https://github.com/apache/cordova-plugin-device
Console cordova plugin: https://github.com/apache/cordova-plugin-console
cordova plugin add https://github.com/apache/cordova-plugin-console
http://blog.revivalx.com/2014/11/14/implement-push-notifications-for-android-and-ios-phonegap-part-3/
Here is my code that uses ngCordova with PushPlugin. The regid comes in the same callback for event 'pushNotificationReceived' for android. Here is the code I use within the callback for that event to receive the regid from GCM:
Checking for (notification.event === 'registered') is the most important.
$rootScope.$on('pushNotificationReceived', function(event, notification) {
//console.log("result: " + JSON.stringify(event));
console.log("result: " + JSON.stringify(notification));
console.log('Success: Inside the push notification received callback with this payload JSON' + notification);
if(( platform == 'android' || platform == 'Android' ) && notification.regid && (notification.event === 'registered'))
{
var googDevToken = notification.regid;
console.log(googDevToken);
}
});
Related
i am creating ionic app where i want to download a image which is dynamic and using cordova file transfer plugin but its not working kindly check where i did the mistake .
Error :- url is not defined ,Cannot read property 'split' of undefined
$
scope.downloadImage = function() {
$http.get('http://sabkideal.com/phpapi_/cashback.php').success(function(response) {
$scope.data = response;
for (var i=0 ;i <response.length; i++)
{
var url = response[i].image;
var deal = response[i].id;
//url showing the same url every time i click and not jumping to next statement when click on send image download .
console.log(deal);
console.log(url);
var filename = url.split("/").pop ;
console.log(filename);
var targetPath = encodeURI(cordova.file.dataDirectory + fileName);
console.log(targetPath);
var options = {};
var trustHosts = true;
}
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(
function(result) {
alert('Download success');
refreshMedia.refresh(targetPath);
},
function(err) {
alert('Error: ' + JSON.stringify(err));
},
function(progress) {
// progressing download...
})
});
}
Make sure the data return is not undefined. By implement the checking you can check whether the data is undefined or not. Use then instead of success because it is deprecated in Angular 1.5 and below
$http.get('http://sabkideal.com/phpapi_/cashback.php').then(function(response) {
$scope.data = response.data;
// Need to check response data so that it is not undefined
if ($scope.data !== undefined && $scope.data !== null && $scope.data !=="") {
for (var i=0 ;i <$scope.data.length; i++)
{
// Checking also need to be done here
if ($scope.data[i].image !== undefined && $scope.data[i].image
!==null && $scope.data[i].image !== "") {
var url = $scope.data[i].image;
var filename = url.split("/").pop ;
}
i want to include the navigator.globalization so i use this tutorial enter link description here
this code:
.run(function($ionicPlatform, $translate) {
$ionicPlatform.ready(function() {
if(typeof navigator.globalization !== "undefined") {
navigator.globalization.getPreferredLanguage(function(language) {
$translate.use((language.value).split("-")[0]).then(function(data) {
alert("SUCCESS -> " + data);
}, function(error) {
alert("ERROR -> " + error);
});
}, null);
}
});
my problem ,this code the alert is not displayed
You have it just with
window.navigator.userLanguage || window.navigator.language;
First check the result of
if(typeof navigator.globalization !== "undefined") {
If its false, the rest of the code will be skipped, because you dont have the plugin.
To get the plugin:
cordova plugin add cordova-plugin-globalization
Hi in my application i am setting the values in login controller and getting in all the other js files, other than this how to use a common service for setting storage and getting that storage in required js files
My login controller
app.controller('LoginController',function(loginService, $rootScope,$scope, $http,$location) {
$scope.login = function () {
$scope.log=loginService.getLogin( $scope.emailId , $scope.password).
then(function (response) {
console.log($scope.log);
console.log(response)
if (response.data.LoginVerificationResult.length === 0) {
alert('details are not Available for this emailId');
$scope.error=true;
} else {
$rootScope.name=response.data.LoginVerificationResult[0].UserName;
$scope.abc=response.data.LoginVerificationResult[0].UserType
console.log($scope.abc+"from.......");
sessionStorage.setItem("EmaiId",$scope.emailId);
sessionStorage.setItem("User Id",response.data.LoginVerificationResult[0].UserID);
sessionStorage.setItem("UserName",response.data.LoginVerificationResult[0].UserName);
sessionStorage.setItem("UserType",response.data.LoginVerificationResult[0].UserType);
$scope.UserType = sessionStorage.getItem("UserType");
console.log($scope.UserType +"from login controller")
$location.path('/dashboard')
}
});
};
});
My changepassword file
app.controller("ChangePwdController", function($scope, $http, $location,
BaseUrl, changePwdService) {
//$scope.roleId = sessionStorage.getItem("Role ID");
/* $scope.UserType = sessionStorage.getItem("UserType");*/
$scope.username = sessionStorage.getItem("UserName");
$scope.userType = sessionStorage.getItem("UserType");
$scope.EmpName=sessionStorage.getItem("EmpName");
$scope.patientName=sessionStorage.getItem("PatientName")
$scope.changePwd = function() {
$scope.emailAddress = sessionStorage.getItem("EmaiId");
console.log($scope.emailAddress)
var data = {
'emailAddress' : $scope.emailAddress,
'currentPassword' : $scope.opassword,
'newPassword' : $scope.npassword
};
console.log("Hi")
$scope.pwd=changePwdService.postChangePwd(data).success(
function(resp) {
$scope.PostDataResponse = data;
console.log($scope.pwd)
console.log($scope.PostDataResponse);
if (resp.ResetPasswordResult === true) {
alert("Successfully changed");
console.log("success")
$location.path('/dashboard');
} else {
console.log("fail")
alert("Enter valid current password")
}
})
}
})
Is there any alternative way to set and get in one file
There are ways in which you can achieve the same. Please refer this here.
myApp.services.factory('GCMHelper', ($q)->
pushNotification = {}
_init = ()->
defer = $q.defer()
ionic.Platform.ready(()->
pushNotification = window.plugins.pushNotification;
window.onNotification = (res)->
console.log('onNotification', res)
defer.resolve()
)
return defer.promise
return {
register: ()->
_init().then(()->
pushNotification.register(
(res)->
console.log('gcm register success', res)
(err)->
console.log('gcm register err', err)
{
"senderID": "*********",
"ecb": "onNotification"
}
);
)
}
)
in controller:
GCMHelper.register()
(Please excuse my poor English)
I'm tring Cordova PushPlugin with Cordova 4.2 and Ionic beta 14, it got success callback every time with "OK" string, but ecb onNotification never fired, and no error at console. I almost have no ideal with that..., any one help?
Use the following for Push Notification in Android and iOS. It will work properly for you. After install the app, user will need to open the app for call ecb methods. In iOS, PushNotifcation's register success method will returns the mobile register id in result but in android, it will return only OK. In Android, onNotificationGCM method will be called for two type event 1) RegisterId and 2) Notification Message. I have also added the showNotificationAPN/GCM method for show notification popups with $ionicPopup.alert().
.run(function ($ionicPlatform, PushProcessingService) {
$ionicPlatform.ready(function () {
try {
PushProcessingService.initialize();
} catch (e) {
//hide event
}
})
})
.factory('PushProcessingService', ["$window", "$ionicPopup", function ($window, $ionicPopup) {
function onDeviceReady() {
var pushNotification = window.plugins.pushNotification;
if (ionic.Platform.isAndroid()) {
pushNotification.register(gcmSuccessHandler, gcmErrorHandler, {'senderID': 'XXXXXXXXXXXXXX', 'ecb': 'onNotificationGCM'});
} else if (ionic.Platform.isIOS()) {
var config = {
"badge": "true",
"sound": "true",
"alert": "true",
"ecb": "pushCallbacks.onNotificationAPN"
};
pushNotification.register(gcmSuccessHandler, gcmErrorHandler, config);
}
var addCallback = function addCallback(key, callback){
if(window.pushCallbacks == undefined){
window.pushCallbacks = {};
}
window.pushCallbacks[key] = callback({registered:true});
}
}
function gcmSuccessHandler(result) {
console.log("Register push notification successfully : " + result);
if (ionic.Platform.isIOS()) {
var mobileType = "ios";
var mobileRegisterId = result;
// Save the ios mobile register Id in your server database
// call the following method on callback of save
addCallback("onNotificationAPN", onNotificationAPN);
}
}
function gcmErrorHandler(error) {
console.log("Error while register push notification : " + error);
}
return {
initialize: function () {
document.addEventListener('deviceready', onDeviceReady, false);
},
registerID: function (id) {
var mobileType = "android";
// Save the android mobile register Id in your server database
console.log("RegisterId saved successfully.");
},
showNotificationGCM: function (event) {
$ionicPopup.alert({
title: "Pajhwok Notification",
subTitle: event.payload.type,
template: event.payload.message
});
},
showNotificationAPN: function (event) {
$ionicPopup.alert({
title: event.messageFrom + "..",
subTitle: event.alert,
template: event.body
});
}
}
}])
onNotificationAPN = function(event) {
if (!event.registered) {
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.showNotificationAPN(event);
} else {
console.log("Registered successfully notification..");
}
}
function onNotificationGCM(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.registerID(e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.showNotificationGCM(e);
break;
case 'error':
alert('<li>ERROR :' + e.msg + '</li>');
break;
default:
alert('<li>Unknown, an event was received and we do not know what it is.</li>');
break;
}
}
I tested my app in the iOS emulator and noticed that the gps does not work.
In the emulator I set the location to "Apple"
and installed the corodova plugin by: "cordova plugin add org.apache.cordova.geolocation".
Here is my Code:
angular.module('home', ['services'])
.controller('homeCtrl',
function ($scope, $location, $state, serverAPI, $ionicPopup) {
$scope.buttonType = "icon ion-search";
$scope.buttonDisable = false;
$scope.text = 'Search';
var UID = JSON.parse(window.localStorage.getItem('Credentials')).UID;
serverAPI.getUserData(UID, function (data) {
$scope.userName = data.userName;
$scope.points = data.points;
$scope.fotoId = data.fotoId;
console.log(data);
});
$scope.click = function () {
$scope.buttonDisable = true;
$scope.text = 'Searching';
$scope.buttonType = 'icon ion-loading-a';
// //Grap geoLocation
var location = navigator.geolocation.getCurrentPosition(saveGeoData, onError);
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
};
var saveGeoData = function (geoData) {
console.log("nach geo");
var myPosition = {
'longitude': geoData.coords.longitude,
'latitude': geoData.coords.latitude
};
console.log("ss");
console.log(myPosition.latitude);
window.localStorage.setItem('myPosition', JSON.stringify(myPosition));
//If geoloaction is saved successfully => Send geodata to server to receive teammate
sendToServer(myPosition);
}
//Send current location to Server to receive teammate
var sendToServer = function (myPosition) {
serverAPI.searchPartnerToPlayWith(myPosition.longitude, myPosition.latitude, UID, function (data) {
//No other players around you. Server returns -1
if (data == -1) {
$ionicPopup.alert({
title: 'Too bad :(',
template: 'Unfortunateley there are no other players around you. Try it some other time!'
});
} else {
window.localStorage.setItem('teammate', data.username);
window.localStorage.setItem('isEnummeration', data.taskType);
window.localStorage.setItem('task', data.task);
var teammatePosition = {
'longitude': data.longitude,
'latitude': data.latitude
};
window.localStorage.setItem('teammatePosition', teammatePosition);
//TODO: data.fotoId => request foto from server
$state.go('tab.play-screen');
}
})
}
};
})
When the function click is called, it just stops in Line:
var location = navigator.geolocation.getCurrentPosition(saveGeoData, onError);
Do you have a guess whats my problem? In the browser it works just fine.
Thanks!
Make sure you include this file into your project.
https://github.com/apache/cordova-plugin-geolocation/blob/master/www/geolocation.js
It can be high probability cause from there, this function not exist in your project, getCurrentPosition.