uniapp中检查版本,提示升级app,安卓下载apk,ios跳转应用商店
uniapp中检查版本,提示升级app,安卓下载apk,ios跳转应用商店
##使用方法:
可以在app.vue
的onLaunch
中调用appUpdate
,打开app就会检测
onLaunch: function () {appUpdate()
},
完整代码如下:
//APP更新
import {queryAppVersion} from "@/apis/app";// 比较版本号:v1 < v2 返回 -1,v1 > v2 返回 1,相等返回 0
function compareVersions(v1, v2) {const v1Parts = v1.split('.').map(Number);const v2Parts = v2.split('.').map(Number);const maxLength = Math.max(v1Parts.length, v2Parts.length);for (let i = 0; i < maxLength; i++) {const part1 = v1Parts[i] || 0;const part2 = v2Parts[i] || 0;if (part1 > part2) return 1;if (part1 < part2) return -1;}return 0;
}async function checkAndroid(remoteRes) {let curVersion = uni.getAppBaseInfo().appVersionconst {appDownloadUrl, izForceFlush, appVersion} = remoteRes;if (compareVersions(appVersion, curVersion) === 1) {uni.showModal({title: "提示",content: "发现新版本,立即升级!",confirmText: "确定",cancelText: "取消",showCancel: izForceFlush !== '1',success: function (res) {if (res.confirm) {uni.showLoading({title: '下载中',mask: true});uni.downloadFile({url: appDownloadUrl, // 这个是最新版本apk包的地址success: (res) => {uni.hideLoading();if (res.tempFilePath) {plus.runtime.install(res.tempFilePath, {force: true}, _res => {uni.showToast({title: "更新成功,重启中",duration: 1500,});plus.runtime.restart();});} else {uni.showToast({title: "下载失败!",icon: "none",});}},fail(err) {uni.showToast({title: "下载失败!",icon: "none",});}})}}})}
}// TODO 你的appStore中的id
const appleId = '';async function checkIos(remoteRes) {const {iosForceFlush, iosAppVersion} = remoteRes;let curVersion = uni.getAppBaseInfo().appVersionuni.request({url: `http://itunes.apple.com/cn/lookup?id=${appleId}`,method: 'POST',success: (res) => {if (res.data.results && res.data.results.length) {const onlineVersion = res.data.results[0].version;// 服务器版本 > 当前版本 && appStore版本 > 当前版本,则提示更新if (compareVersions(onlineVersion, curVersion) === 1 && compareVersions(iosAppVersion, curVersion) === 1) {uni.showModal({title: '更新提示',content: '发现新版本,是否要更新?',showCancel: iosForceFlush !== '1',success(res) {if (res.confirm) {plus.runtime.launchApplication({action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`},function (e) {console.log(e.message);});}}})}}}});
}export default async function appUpdate() {// #ifdef APP-PLUSlet system = uni.getSystemInfoSync();const [err, res] = await queryAppVersion();if (err || !res.result) return;if (system.platform === 'ios') {checkIos(res.result);}if (system.platform === 'android') {checkAndroid(res.result);}// #endif
}
queryAppVersion是后台管理配置的版本信息
对比方法:
- 安卓:比对当前版本和后台管理版本,提示更新
- IOS:比对当前版本和后台管理版本 && 比对当前版本和应用商店版本,满足则提示更新
- 同时也会校验后台管理是否配置强制更新,是的话,不显示关闭弹框按钮