cordova-plugin-app-version外掛的使用
阿新 • • 發佈:2019-02-06
開發專案的時候自動更新功能呢,需要獲取app的版本,cordova-plugin-app-version可以用來的獲取版本號,可以用命令列:cordova plugin add cordova-plugin-app-version,或者在配置檔案config.xml、package.json進行配置。
cordova.getAppVersion.getVersionNumber()就可以獲取當前的版本
getServerVersion: function (curVersion) {
var deferred = $q.defer(),
promise;
if (curVersion) {
promise = $http.get(CONFIG.url.version, {params: {version: curVersion}});
} else {
promise = $http.get(CONFIG.url.version);
}
promise.then(function (response) {
deferred.resolve(response.data.data.versions);
}).catch(function (error) {
deferred.reject(error);
});
return deferred.promise;
},
getLocalVersion: function () {
var deferred = $q.defer();
**cordova.getAppVersion.getVersionNumber()**.then(function (localVersion) {
deferred.resolve(localVersion);
}).catch(function (error) {
deferred.reject(error);
});
return deferred.promise;
},
checkUpdate: function () {
var self = this,
localVersion;
this.getLocalVersion().then(function (response) {
localVersion = response;
return self.getServerVersion(response);
}).then(function (serverVersions) {
var latestVersion = _.isArray(serverVersions) ? _.first(serverVersions) : serverVersions,
laterThanServer = commonService.laterThan(localVersion, latestVersion.number),
isForceUpdate = _.some(_.initial(serverVersions), function (item) {
return item.flag === 1;
});
commonService.setItem("latestVersion", latestVersion);
return laterThanServer && isForceUpdate;
}).then(function (isForce) {
isForce && commonService.confirm(i18n.need_update_label, i18n.force_update_tip).then(function (res) {
if (res) {
checkUpdateEnv(isForce);
} else {
ionic.Platform.exitApp();
}
});
}).catch(function (reason) {
console.log("version compare filed : " + JSON.stringify(reason));
});
}
但是有一點需要注意的是執行此語句,必須等待DOM元素載入完畢。簡單一點就是,若是在傳統的javaScript中用到,需要配合著window.onload使用,或者 ionic.Platform.ready中
ionic.Platform.ready(function () {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
window.cordova.plugins.Keyboard.disableScroll(true);
apiService.checkUpdate();
}
try {
$cordovaStatusbar.style(0);
checkNetworkState();
checkSystemVersion();
$ionicPlatform.is("Android") && $ionicPlatform.registerBackButtonAction(registerBackButton, 101);
} catch (e) {
console.warn("some thing error when app launched: " + e.message);
}
autoLogin();
});