我已尝试过关于Cordova文档的this指南,但它似乎无效。
这是我的代码:
我已将<plugin name="NetworkStatus" value="CDVConnection" />
添加到config.xml
。
此脚本发送到我的index.html
:
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
alert("1"); // runs this alert
checkConnection();
}
function checkConnection() {
var networkState = Connection.CELL;
alert("2"); // doesn't run this
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
</script>
var networkState = Connection.CELL;
似乎导致了问题,因为它没有运行以下警报,我也尝试了navigator.connection.type
,但同样的事情发生了。
当我在Chrome中运行应用时,控制台会输出以下错误:
Uncaught ReferenceError: Connection is not defined
有谁知道如何解决这个问题?
干杯
答案 0 :(得分:21)
我终于解决了问题!! - 从头开始重新开始并执行以下操作:
命令行:
sudo npm install -g cordova
cordova create hello com.example.hello HelloWorld
cd hello
cordova platform add ios
cordova platforms ls //This will list ios
cordova plugin add org.apache.cordova.network-information
cordova build
然后将我的文件(HTML,Javascript等)拖到platforms/ios/www/
文件夹中。
在xcode中打开hello.xcodeproj
。
编辑config.xml并添加以下行:
<feature name="NetworkStatus">
<param name="ios-package" value="CDVConnection" />
</feature>
然后在我的索引文件中,我使用了JavaScript:
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
if(navigator.network.connection.type == Connection.NONE){
alert("nocon");
}else{
alert("yescon");
}
}
</script>
然后在iPhone / iPad模拟器中运行它,如果有连接则输出“yescon”,如果没有则输出“nocon”!!
希望这有帮助!
答案 1 :(得分:0)
检查您是否已将您的Cordova.js文件包含在html中。
<script type="text/javascript" src="cordova.js"></script>
并更改项目的App/Supporting Files/Cordova.plist
。
<key>Plugins</key>
<dict>
<key>NetworkStatus</key>
<string>CDVConnection</string>
</dict>
答案 2 :(得分:0)
这对我有用:
if(navigator.network.connection.type == Connection.NONE){
//no connection
}else{
//You are connected.
}
虽然我查看了文档,看起来使用这些行有所不同:
var networkState = navigator.network.connection.type;
navigator.network.connection.type设置为Connection.CELL_2G
。
是var networkState = Connection.CELL_2G;
吗?