uniapp小程序实现更新操作提示用户升级
引言
小程序更新时,为了防止小程序由于热启动或者需要在登录时候添加新的缓存,无法获取新的小程序操作等原因,因此需要通过设置,提示用户升级小程序
获取小程序版本是否需要更新以及更新操作
1.App.vue文件中实现获取更新方法
// 在 methods 中实现方法
autoUpdate() {
// 更新的功能基础库要1.9.90以上版本才支持,要做低版本的兼容处理
if (uni.canIUse('getUpdateManager')) {
// uni.getUpdateManager接口,可以获知是否有新版本的小程序、新版本是否下载好以及应用新版本的能力,会返回一个UpdateManager实例
const updateManager = uni.getUpdateManager();
// 检查小程序是否有新版本发布,onCheckForUpdate:当小程序向后台请求完新版本信息,会通知这个版本告知检查结果
updateManager.onCheckForUpdate(res => {
// 请求完新版本信息的回调
if (res.hasUpdate) {
// 检测到新版本,需要更新,给出提示
showModal({ content: '检测到新版本,是否下载新版本并重启小程序' }).then(res => {
if (res.confirm) {
this.downLoadAndUpdate(updateManager);
} else if (res.cancel) {
showModal({ content: '本次版本更新涉及到新功能的添加,旧版本将无法正常使用', showCancel: false, confirmText: '确认更新' }).then(res => {
if (res.confirm) this.downLoadAndUpdate(updateManager);
});
}
});
}
});
} else {
// 在最新版本客户端上体验小程序
showModal({ content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试' });
}
},
// 下载小程序最新版本并重启
downLoadAndUpdate(updateManager) {
showLoading({ title: '正在下载' });
// 等待下载更新小程序新版本,onUpdateReady:当新版本下载完成回调
updateManager.onUpdateReady(() => {
uni.hideLoading();
// applyUpdate:强制当前小程序应用上新版本并重启
updateManager.applyUpdate();
// 可在此处添加清除缓存跳转首页操作,由于本人在通过其他判断方式跳转首页,故不再此处跳转
// ....
});
// 当新版本下载失败回调
updateManager.onUpdateFailed(() => {
uni.hideLoading();
// 下载新版本失败
showModal({ content: '新版本已经上线了,请删除当前小程序,重新搜索打开' })
.then(() => {
// 点击确定,清空小程序缓存,是小程序情况而定
clearPartStorageSync();
setTimeout(() => {
// 跳转到首页
uni.reLaunch({ url: '/pages/common/homePage/index' });
}, 100);
})
.catch(() => {
// 点击取消,同理
clearPartStorageSync();
setTimeout(() => {
uni.reLaunch({ url: '/pages/common/homePage/index' });
}, 100);
});
});
}
2.在App.vue的 onShow 里面运行
// 注意,需要在 onShow 中运行,切勿在其他生命周期中运行,防止小程序热启动导致不生效
onShow() {
this.autoUpdate();
}
3.App.vue中使用到的提示框封装方法
export const showModal = ({ content, showCancel = true, confirmText = '确定' }) => {
return new Promise((resolve, reject) => {
uni.showModal({
title: '提示',
content: content,
showCancel,
confirmText,
success: (res) => {
resolve(res)
},
fail: (err) => {
reject(err)
}
})
})
}
export const showLoading = ({ title }) => {
return uni.showLoading({
title,
mask: true
})
}
此方法也是通过网上资料查找和我项目自身的情况改造的,如有错误,欢迎各位指出
最后,再次强调一遍,不可把获取新小程序的方法放到 onShow 之外的周期里!!!