微信小程序新版本发布之后,用户使用依然是旧版本,这是因为在微信有缓存且不会及时更新至新版本。所以想让用户更新到新版本,可以通过两种方式,一种是卸载小程序后再重新搜索下载(显然这种方式有些麻烦),另一种则是小程序中加个功能:给予用户版本更新提示并自动下载安装新版本。
UpdateManager 对象,用来管理小程序的更新的,下载更新的功能块代码块如下(可以把下面的代码写到一个方法里面,在 app.js 定义的 App 实例的 onLaunch 回调中调用即可)
const updateManager = wx.getUpdateManager();
updateManager.onCheckForUpdate(function(res) {
// 请求完新版本信息的回调
console.log(res.hasUpdate);
if (res.hasUpdate) {
wx.showModal({
title: '更新提示',
content: '小程序有新的版本,是否下载并更新?',
success: function(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.onUpdateReady(function() {
let timer1 = setTimeout(() => {
updateManager.applyUpdate();
clearTimeout(timer1);
}, 2000);
});
updateManager.onUpdateFailed(function(res) {
console.log(res);
let timer2 = setTimeout(() => {
wx.showToast({
title: '更新失败,请下次再试',
icon: 'none',
duration: 2000
});
clearTimeout(timer2);
}, 2000);
});
}
}
});
}
});
微信在小程序冷启动时自动检查更新,不需由开发者主动触发!