-
-
Save Rakonda/323bd0d0a751c75a91c44a08d82bba40 to your computer and use it in GitHub Desktop.
Async navigator.connection.type service for Ionic Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myApp = angular.module('myApp').service('CordovaNetwork', ['$ionicPlatform', '$q', function($ionicPlatform, $q) { | |
// Get Cordova's global Connection object or emulate a smilar one | |
var Connection = window.Connection || { | |
"CELL" : "cellular", | |
"CELL_2G" : "2g", | |
"CELL_3G" : "3g", | |
"CELL_4G" : "4g", | |
"ETHERNET" : "ethernet", | |
"NONE" : "none", | |
"UNKNOWN" : "unknown", | |
"WIFI" : "wifi" | |
}; | |
var asyncGetConnection = function () { | |
var q = $q.defer(); | |
$ionicPlatform.ready(function () { | |
if(navigator.connection) { | |
q.resolve(navigator.connection); | |
} else { | |
q.reject('navigator.connection is not defined'); | |
} | |
}); | |
return q.promise; | |
}; | |
return { | |
isOnline: function () { | |
return asyncGetConnection().then(function(networkConnection) { | |
var isConnected = false; | |
switch (networkConnection.type) { | |
case Connection.ETHERNET: | |
case Connection.WIFI: | |
case Connection.CELL_2G: | |
case Connection.CELL_3G: | |
case Connection.CELL_4G: | |
case Connection.CELL: | |
isConnected = true; | |
break; | |
} | |
return isConnected; | |
}); | |
} | |
}; | |
}]); | |
myApp.controller('AppCtrl', function(CordovaNetwork){ | |
CordovaNetwork.isOnline().then(function(isConnected) { | |
alert(isConnected); | |
}).catch(function(err){ | |
console.log(err); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment