I'm developing cross platform applications. I'm able to request access to location using the Phone Gap API. If the user clicks okay, then I'm able to get the latitude and longitude using PhoneGap API and send it to the server.
However, I'm facing issues if the user clicks "Don't Allow" initially. After that, if he tries to refresh page, I want the device to show the popup again to request access to the location.
How do we do that in Single Page Applications?
var loadPanelMessage = ko.observable("Sipping..."),
loadPanelVisible = ko.observable(false),
lat = ko.observable(''),
lon = ko.observable('');
navigator.geolocation.getCurrentPosition(onSuccess, onError);
var onSuccess = function (position) {
lat(position.coords.latitude);
lon(position.coords.longitude);
timestamp(position.timestamp);
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
//How should I handle the error, so that it asks for Geolocation again?
}
You cannot reshow that popup, it is shown by iOS and once user click's "Don't Allow" you cannot force that popup. All you can do is to let your user know about the situation and direct the user to iOS settings to enable location services for your app.
Here is a nice read about the problem:
https://medium.com/on-startups/96fa4eb54f2c
Based on the cordova plugins here org.apache.cordova.geolocation
All you need to do is a watchPosition to check the PositionError, and use also the cordova-plugin-dialogs to show the native notification
navigator.geolocation.watchPosition((function(_this) {
return function(position) {
// Do something here
};
})(this), function(error) {
var errorButton, errorMsg, errorTitle;
errorTitle = "Location Services";
errorButton = "Ok";
if (error.code === 1) {
errorMsg = "\"AppName\" needs access to your location. Please turn on Location Services in your device settings.";
}
if (error.code === 2) {
errorMsg = "This device is unable to retrieve a position. Make sure you are connected to a network";
}
if (error.code === 3) {
errorMsg = "This device is unable to retrieve a position. Make sure you have Location Services enabled for \"AppName\"";
}
if (error.code === 1 || error.code === 2 || error.code === 3) {
return navigator.notification.alert(errorMsg, errorDismissed(), errorTitle, errorButton);
}
}, {
enableHighAccuracy: true,
maximumAge: 20000,
timeout: 10000
});
Related
Building an app with RN I use the following to receive user's location :
navigator.geolocation.getCurrentPosition(
(position) => {
//do stuff with location
},
(error) => {
//error or locaiton not allowed
},
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
Which immediately invokes the inquiry for user to accept geolocation permissions. What I'm trying to achieve now is to have an explicit screen before prompting user to click on a button to accept those permissions. In order to get there, I need some way to check if he has accepted those permissions before or not. Caching it in storage would be a bad solution - it might go out of sync if user changes permissions in settings.
How can I check if user has accepted geolocation permissions without triggering the permission alert?
You can use this library https://github.com/yonahforst/react-native-permissions to check if user has accepted location permission.
Like this:
Permissions.getPermissionStatus('location')
.then(response => {
this.setState({ locationPermission: response })
})
In v2.x.x of react-native-permissions (https://github.com/react-native-community/react-native-permissions)
import { Platform } from "react-native";
import { PERMISSIONS, request } from "react-native-permissions";
import * as Geolocation from "#react-native-community/geolocation";
try {
request(
Platform.select({
android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
})
).then(res => {
if (res == "granted") {
Geolocation.getCurrentPosition( // do location staffs);
Geolocation.watchPosition( // do watch location staffs );
} else {
// console.log("Location is not enabled");
}
});
} catch (error) {
console.log("location set error:", error);
}
Check this library, this would help you to check location is enabled or not.
https://www.npmjs.com/package/react-native-device-info#isLocationEnabled
Note : Above will not check permission enabled on not. It will just check location truned on or not
I'm building an app which will list the nearest product dealers to the users current location.
When testing on my device iPhone 6 & iPhone 4S I can see that my app doesn't have permission to get the location but when I go to settings I can't see my test app listed to grant it that permission.
Is this due to the way the app is installed when "Run" via Appcelerator Studio? How can I grant a test app permission please?
My code is:
function getCurrentPhoneLocation(callback)
{
Titanium.API.info("get phone location " + Ti.Geolocation.locationServicesEnabled);
if(Ti.Geolocation.locationServicesEnabled)
{
Titanium.API.info("GPS permissions: " + Ti.Geolocation.locationServicesAuthorization + " (" + Ti.Geolocation.AUTHORIZATION_ALWAYS + " | " + Ti.Geolocation.AUTHORIZATION_AUTHORIZED + " | " + Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE + ")");
if (Ti.Geolocation.locationServicesAuthorization == Ti.Geolocation.AUTHORIZATION_ALWAYS || Ti.Geolocation.locationServicesAuthorization == Ti.Geolocation.AUTHORIZATION_AUTHORIZED || Ti.Geolocation.locationServicesAuthorization == Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE)
{
Titanium.API.info("Got permissions - lets go!");
Ti.Geolocation.purpose = 'Get current location';
var currentPhoneLocation = {};
Ti.Geolocation.getCurrentPosition(function(e){
Titanium.API.info("from pos: " + JSON.stringify(e));
if(e.success === false) {
Ti.API.error('Error:' + e.error);
alert("Location is currently unavailable");
callback( false );
} else {
currentPhoneLocation.longitude = e.coords.longitude;
currentPhoneLocation.latitude = e.coords.latitude;
Ti.API.info("Returned Cords: " + JSON.stringify(currentPhoneLocation));
callback();
}
});
}
else
{
Titanium.API.info("No APP permission");
Titanium.UI.createAlertDialog({title:'Location Service', message:'Please grant this app permission to get your location.'}).show();
callback( false );
}
}
else
{
Titanium.API.info("No GPS available");
Titanium.UI.createAlertDialog({title:'Location Service', message:'Please turn on your location services.'}).show();
callback( false );
}
}
You can see my trace code is showing that Ti.Geolocation.locationServicesAuthorization is returning '0'.
[INFO] : get phone location true
[INFO] : GPS permissions: 0 (3 | 3 | 4)
[INFO] : No APP permission
[INFO] : Recieved location: false
No matter how you install it, preferences work the same. You still have to authorise it.
However, a lot of things have changed for permissions in the latest release, and I recommend looking at the documentation to set it up properly. You can find an example app on GitHub
Best way to check if it has been granted is through:
Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS);
Also, I recommend fetching location. The false is actually provided by you. If you granted the app permissions (verified in settings) this should work
Ti.GeoLocation.getCurrentPosition(callback(e){})
I have spent lot of time to find correct cordova plugin for parse push notifications for both Android & iOS platforms.
My requirements are:
To receive parse push notification (in both android & iOS)
Able to store all the incoming push notifications in mobile local storage Sqlite.
I have tried all the below parse push cordova plugins for both Android & iOS platforms.
https://github.com/avivais/phonegap-parse-plugin
https://github.com/taivo/parse-push-plugin
https://github.com/campers/parse-push-plugin
https://github.com/manishiitg/parse-push-plugin
For Android: All the above plugins are working perfectly to fulfill my above mentioned requirements.
For iOS: Only 1st plugin i.e https://github.com/avivais/phonegap-parse-plugin is working. And that too i was not able to save the notifications in local storage sqlite. That means only my 1st requirement is fulfilled but not my 2nd requirement.
All the github pages of remaining plugins (i.e 2nd, 3rd, 4th) states that:
"Please note that I've only worked on the Android aspect of this fork. The iOS side is not yet up to date."
Is there any plugin which will work for both Android & iOS platforms to fulfill my 2 requirements?
(or)
If there is no common plugin for both the platforms, then how can I store the incoming plugins in iOS sqlite?
Please help me. Thanks in advance.
I happen to maintain https://github.com/taivo/parse-push-plugin
It looks like you caught my fork at its infancy. I picked it up when the upstream fork seemed stagnant for a while and at that time I was only addressing the Android aspect. Since then I've provided full iOS support. And it works for parse-server as well as the out-going parse.com. I also did one better and made installation just a matter of
cordova add https://github.com/taivo/parse-push-plugin
and writing a few config.xml tags to indicate server url, and app id.
That should take out the big pain of manually messing with Android Manifest, Java, and Objective C when setting up the plugin.
It should now meet or exceed your requirement. To receive push notification and store in sqlite, all you have to do is set an event handler in javascript. Be sure to wrap it with some sort of device ready or platform ready event handler to ensure the plugin has properly loaded.
$ionicPlatform.ready(function(){
if(window.ParsePushPlugin){
ParsePushPlugin.on('receivePN', function(pn){
console.log('yo i got this notif:' + JSON.stringify(pn) );
//
// do your sqlite storage here
//
});
}
});
You just might be interested in the Azure Push Notifications. It combines both Push notification services so you can send messages to both devices from one central point.
I quote:
Notification Hubs A scalable, cross-platform solution for sending push
notifications to mobile devices, Notification Hubs works well with
Cordova apps. Notification Hubs manages the registrations with each
PNS. More important, Notification Hubs lets you create template
registrations so you can send messages to all registered devices,
regardless of platform, with only a single line of code. You can also
use tags to send targeted notifications only to devices with specific
registrations. For more information about Notification Hubs, see the
Azure Web site at aka.ms/nkn4n4.
Here i have a helper class for registering your device with the pushnotification service. For sending push notifications, you can use an azure portal and send styled push notifications in json format.
var Pushman = {
Initialize: function (hubConnString, hubName, gcmSenderId, callbackRegistered, callbackUnRegistered, callbackInlineNotification, callbackBackgroundNotification, callbackError) {
//store connection and callback information on app startup for Push Registration later
Pushman.HubConnectionString = hubConnString;
Pushman.HubName = hubName;
Pushman.GcmSenderId = gcmSenderId;
//callbacks
Pushman.RegisteredCallback = callbackRegistered;
Pushman.UnRegisteredCallback = callbackUnRegistered;
Pushman.NotificationForegroundCallback = callbackInlineNotification;
Pushman.NotificationBackgroundCallback = callbackBackgroundNotification;
Pushman.ErrorCallback = callbackError;
},
RegisterForPushNotifications: function (tags) {
//setup Azure Notification Hub registration
Pushman.Hub = new WindowsAzure.Messaging.NotificationHub(Pushman.HubName, Pushman.HubConnectionString, Pushman.GcmSenderId);
Pushman.Hub.registerApplicationAsync(tags).then(Pushman.onRegistered, Pushman.onError);
//setup PushPlugin registration
Pushman.Push = window.PushNotification;
var push;
//register depending on device being run
if (device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos") {
//android
push = Pushman.Push.init(
{ "android": { "senderID": Pushman.GcmSenderId } }
);
push.on('registration', Pushman.onRegistered);
push.on('notification', Pushman.onAndroidNotification);
push.on('error', Pushman.onError);
} else {
//iOS
push = Pushman.Push.init(
{ "ios": { "alert": "true", "badge": "true", "sound": "true" } }
);
push.on('registration', Pushman.onRegistered);
push.on('notification', Pushman.onIOSNotification);
push.on('error', Pushman.onError);
}
},
UnRegisterForPushNotifications: function () {
if (Pushman.Hub != null) {
//dont pass through error handler
//unreg azure
Pushman.Hub.unregisterApplicationAsync()
.then(Pushman.onUnRegistered, null);
//unreg native
Pushman.Push.unregister(Pushman.onUnRegistered, null);
}
},
onRegistered: function (msg) {
Pushman.log("Registered: " + msg.registrationId);
//only call callback if registrationId actually set
if (msg.registrationId.length > 0 && Pushman.RegisteredCallback != null) {
Pushman.RegisteredCallback(msg);
}
},
onUnRegistered: function () {
Pushman.log("UnRegistered");
if (Pushman.UnRegisteredCallback != null) {
Pushman.UnRegisteredCallback();
}
},
onInlineNotification: function (msg) {
Pushman.log("OnInlineNotification: " + msg);
if (Pushman.NotificationForegroundCallback != null) {
Pushman.NotificationForegroundCallback(msg);
}
},
onBackgroundNotification: function (msg) {
Pushman.log("OnBackgroundNotification: " + msg);
if (Pushman.NotificationBackgroundCallback != null) {
Pushman.NotificationBackgroundCallback(msg);
}
},
onColdStartNotification: function (msg) {
Pushman.log("OnColdStartNotification: " + msg);
if (Pushman.NotificationBackgroundCallback != null) {
Pushman.NotificationBackgroundCallback(msg);
}
},
onError: function (error) {
Pushman.log("Error: " + error);
if (Pushman.ErrorCallback != null) {
Pushman.ErrorCallback(error);
}
},
onAndroidNotification: function (e) {
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
Pushman.onRegistered("Registered");
}
break;
case 'message':
if (e.foreground) {
//if this flag is set, this notification happened while app in foreground
Pushman.onInlineNotification(e.payload.message);
} else {
//otherwise app launched because the user touched a notification in the notification tray.
if (e.coldstart) {
//app was closed
Pushman.onColdStartNotification(e.payload.message);
}
else {
//app was minimized
Pushman.onBackgroundNotification(e.payload.message);
}
}
break;
case 'error':
Pushman.onError(e.msg);
break;
default:
Pushman.onError("Unknown message");
break;
}
},
onIOSNotification: function (event) {
//TODO: not sure how ios works re cold start vs inline msg types?
if (event.alert) {
navigator.notification.alert(event.alert);
}
if (event.badge) {
Push.setApplicationIconBadgeNumber(app.successHandler, app.errorHandler, event.badge);
}
},
tokenHandler: function (result) {
// iOS - not sure its use though appears somewhat important
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
alert('device token = ' + result);
},
log: function (msg) {
console.log(msg);
},
}
///"class" variables - not sure how to put them into the js "class"
Pushman.Push = null;
Pushman.Hub = null;
Pushman.HubConnectionString = null;
Pushman.HubName = null;
Pushman.GcmSenderId = null;
Pushman.NotificationForegroundCallback = null;
Pushman.NotificationBackgroundCallback = null;
Pushman.RegisteredCallback = null;
Pushman.UnRegisteredCallback = null;
Pushman.ErrorCallback = null;
I did not write this myself, all credit goes to this guy.
Then you just need to initialize the plugin when the application starts:
//azure notificationshub connection information
notificationHubPath = "notificationhub name";
connectionString = "notificatin hub connectionstring";
//sender id for google cloud services
var senderIdGCM = "sender id from google gcm";
//tag registration (csv string), can be empty but not undefined
var registrationTagsCsv = ""; //test1, test2
var app = {
Initialize: function () {
//reg for onload event
this.AppStart();
},
AppStart: function () {
"use strict";
document.addEventListener('deviceready', app.onLoad, false);
document.addEventListener('deviceready', onDeviceReady.bind(this), false);
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener('pause', onPause.bind(this), false);
document.addEventListener('resume', onResume.bind(this), false);
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
},
onLoad: function () {
app.log("Initializing...");
//setup push notifications
Pushman.Initialize(connectionString, notificationHubPath, senderIdGCM,
app.onNotificationRegistered, app.onNotificationUnRegistered,
app.onNotificationInline, app.onNotificationBackground, app.onNotificationError);
//hookup cmd buttons
app.registerForPush();
//$("#register").click(app.registerForPush);
//$("#unregister").click(app.unRegisterForPush);
app.onAppReady();
},
registerForPush: function (a, c) {
app.log("Registering...");
//register for tags
Pushman.RegisterForPushNotifications(registrationTagsCsv);
},
unRegisterForPush: function (a, c) {
app.log("UnRegistering...");
//register for tags
Pushman.UnRegisterForPushNotifications();
},
onAppReady: function () {
app.log("Ready");
},
onNotificationRegistered: function (msg) {
app.log("Registered: " + msg.registrationId);
},
onNotificationUnRegistered: function () {
app.log("UnRegistered");
},
onNotificationInline: function (data) {
app.log("Inline Notification: " + data);
},
onNotificationBackground: function (data) {
app.log("Background Notification: " + data);
},
onNotificationError: function (error) {
app.log("Error: " + error);
},
log: function (msg) {
console.log(msg);
},
};
If you want to store the messages then you just need to add your code for storing to sql where the messages get received. You'll need an azure account to make this work, here you can get a free trail. It will allow you to send up to 1 million push notifications a month free of charge.
I think this article may be of use, it has more of a direct native workaround for your hybrid app to work
http://www.hiddentao.com/archives/2015/04/10/parse-push-notifications-for-your-android-and-ios-cordova-app/.
I'm working on a Cordova android app, and this seems to be a working solution
Goal of the app: get geolocation on each move and log location either when app is in foreground and background.
I've tried so many code and combination but I can't manage to have it working (2 days from now...).
The classic geolocation (getCurrentPosition) is working fine but when we close the app the background geolocation is launched but nothing happen... Function "callbackFn" is never fired.
I'm testing on IOS with xcode > Capabilities Audio & location activated for background activity. I also made working the jQuery sample example given in plugin so I saw it working but never with ionic/angularjs.
Here is the current controller handling the background:
.controller('TestCtrl', function($scope, $timeout, $cordovaBackgroundGeolocation, $ionicPlatform, $window)
{
$scope.lat_geo = "loading lat...";
$scope.long_geo = "loading long...";
//-- Geolocal launch
var options = {
enableHighAccuracy : false,
desiredAccuracy: 0,
stationaryRadius: 1,
distanceFilter: 5,
notificationTitle: 'Background tracking', // <-- android only, customize the title of the notification
notificationText: 'ENABLED', // <-- android only, customize the text of the notification
activityType: 'AutomotiveNavigation',
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false // <-- enable this to clear background location settings when the app terminates
};
$ionicPlatform.ready(function()
{
console.log("[IONIC PLATFORM IS NOW READY]");
//-- First launch a basic geolocalisation to get user acceptance of geosharing ;)
navigator.geolocation.getCurrentPosition(function(location) {
console.log('[GEOLOCAL JS1] Location from Phonegap');
},
function (error){
console.log('[GEOLOCAL JS1] error with GPS: error.code: ' + error.code + ' Message: ' + error.message);
},options);
//-- test adaptation depuis l'app jquery
var callbackFn = function(location) {
console.log('[BackgroundGeoLocation] Update callback: ' + location.latitude + ',' + location.longitude);
};
var failureFn = function(error) {
console.log('[BackgroundGeoLocation] Error: '+error);
};
$cordovaBackgroundGeolocation.configure(callbackFn, failureFn, options);
// Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app.
$cordovaBackgroundGeolocation.start();
//-- Just a timeout to retreive long / lat
$timeout(function()
{
navigator.geolocation.getCurrentPosition(function(location)
{
console.log('[GEOLOCAL JS3] Location from Phonegap');
startPos = location;
$scope.$apply(function () {
$scope.lat_geo = startPos.coords.latitude;
$scope.long_geo = startPos.coords.longitude;
});
console.log("[GEOLOCAL BASIC] OK this time :)");
},
function (error){
console.log('[GEOLOCAL JS3] error with GPS: error.code: ' + error.code + ' Message: ' + error.message);
},options);
}, 3000);
});
//-- End Geolocal
})
I've put all my code (a complete ionic app starter) on github: https://github.com/Jeff86/ionic_ngcordova_backgroundgeo_test/tree/master
I read this article http://ngcordova.com/docs/plugins/backgroundGeolocation/
I see that you should put your code into
document.addEventListener("deviceready", function () { ... });
Do you find any solution?
You definitely don't want to use the std Cordova-geolocation plugin in the bg, it'll kill the battery in no time.
I'm the author of the underlying background-geolocation plugin for Ionic. I've created a New Ionic-based SampleApp.
https://github.com/transistorsoft/cordova-background-geolocation-SampleApp
When i run fb.login() in an ios 6 device using the account setted in Settings/facebook i get the following
operation couldn't be completed (com.facebook.sdk error 2)
in ios 5 the app works perfectly, the problem is the native login
help please ! this is my code
this is the facebook init
this.appId = appId;
var me = this;
document.addEventListener('deviceready', function() {
try {
FB.init({ appId: "294003447379425", status: true, cookie: true, nativeInterface: CDV.FB, useCachedDialogs: false });
} catch (e) {
console.log(e);
}
}, false);
if (!this.appId) {
Ext.Logger.error('No Facebook Application ID set.');
return;
}
var me = this;
me.hasCheckedStatus = false;
FB.Event.subscribe('auth.logout', function() {
// This event can be fired as soon as the page loads which may cause undesired behaviour, so we wait
// until after we've specifically checked the login status.
if (me.hasCheckedStatus) {
me.fireEvent('logout');
}
});
// Get the user login status from Facebook.
FB.getLoginStatus(function(response) {
me.fireEvent('loginStatus');
clearTimeout(me.fbLoginTimeout);
me.hasCheckedStatus = true;
if (response.status == 'connected') {
me.fireEvent('connected');
Ext.Viewport.add(Ext.create('CinePass.view.Main'));
} else {
me.fireEvent('unauthorized');
console.log('noconectado');
Ext.Viewport.add(Ext.create('CinePass.view.LoggedOut'));
}
});
// We set a timeout in case there is no response from the Facebook `init` method. This often happens if the
// Facebook application is incorrectly configured (for example if the browser URL does not match the one
// configured on the Facebook app.)
me.fbLoginTimeout = setTimeout(function() {
me.fireEvent('loginStatus');
me.fireEvent('exception', {
type: 'timeout',
msg: 'The request to Facebook timed out.'
});
Ext.Msg.alert('CinePass', 'Existe un problema con Facebook, se iniciará la aplicación sin conexión a Facebook.', Ext.emptyFn);
Ext.Viewport.add(Ext.create('CinePass.view.Main'));
}, me.fbTimeout);
this is the login
FB.login(
function(response) {
if (response.session) {
alert(response.session);
} else {
alert(response.session);
}
},
{ scope: "email,user_about_me,user_activities,user_birthday,user_hometown,user_interests,user_likes,user_location,friends_interests" }
);
Having the same problem and took me few days to figure this out, there are a number of reasons:
1) The first time you launch your app, if you deny the "Do you allow this app to use your facebook permission", you'll get this error, what you need to do is, go to Setting > General > Facebook > turn on your app OR go to Setting > General > Reset > Reset Location & Privacy (this will reset and ask you the "Do you allow this app to use your facebook permission" again for all app.
2) Slow/No Internet can caused the error
3) Create your certificate again, and go to build.phonegap.com, create a new key for IOS and change the IOS key (This works for me, I have no idea how it works but it does, I notice a significant app file size increase after i use a new IOS Key)
4) If your app is in sand box mode, and your IOS current Facebook account is not an app tester you'll get the error too. I just disable the sand box mode and it works, make sure your Facebook App Setting has the correct bundle ID, if your app is still under developement, put 0 to app store ID.