I'm developing an app where I want to download content (JSON) dynamically from my server. Before the download gets started I want to check if the device is online and my server is reachable.
Using Cordova it's very easy to get the network information (WiFi
, Cellular
, None
, ...). But I've discovered a problem with WiFi networks which need a VPN connection. Without VPN Cordova returns WiFi
but the app can't connect to the server. How can I check if the server is reachable?
I'm using Cordova with Ionic Framework (which uses AngularJS) and AngularJS's $http
function to download my data.
Here is my current isOnline()
service:
function() {
var is_online;
var network_state = navigator.connection.type;
return ((network_state == 'unknown') || (network_state == 'none')) ? false : true;
}
This is how I download the data:
if(isOnline()) {
var url = 'http://domain.com/file.json';
$http({
method: 'GET',
url: url
})
.success(function(data, status, headers, config) {
// save data
})
.error(function(data, status, headers, config) {
// error
});
}
Unfortunately the download function doesn't go to the error function if the server is not reachable.
Thank you very much for your help!
In your WiFi/VPN case I would say that the error function is not hit because your $http is still trying to retrieve the data and doesn't know that the VPN is preventing it from it.
Did you wait for some time till the timeout hits? Try to specify for debugging purposes a low timeout value and check if the error function is then called.