微信小程序启动自动检测版本更新,检测到新版本则提示更新updateManager

效果

  • 有时候小程序自动更新没那么快,且有时候存在缓存,需要删除小程序才能检测更新,这样就不能及时更新到了,所以加个自动检测更新是很有必要的。
  • 效果:小程序启动时,若用户本地与小程序最新版本不一致,就会出现如下弹窗,用户点确定,小程序将会进行更新,效果如下:。
    在这里插入图片描述

代码

app.js加入以下代码:

// app.js
App({
    
    
  onLaunch() {
    
    
    this.globalData.sysinfo = wx.getSystemInfoSync()
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
    
    
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
    
    
      wx.showModal({
    
    
        title: '更新提示',
        content: '新版本已经准备好,是否重启应用?',
        success: function (res) {
    
    
          if (res.confirm) {
    
    
            // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
    
    
      // 新的版本下载失败
      wx.showModal({
    
    
        title: '更新提示',
        content: '新版本下载失败',
        showCancel: false
      })
    })
  },
  globalData: {
    
    
    sysinfo: {
    
    },
  }
})

微信小程序版本更新api

  • wx.getUpdateManager()获取全局唯一的版本更新管理器,用于管理小程序更新
  • UpdateManager.onCheckForUpdate监听向微信后台请求检查更新结果事件
  • UpdateManager.onUpdateReady监听小程序有版本更新事件。客户端主动触发下载(无需开发者触发),下载成功后回调
  • UpdateManager.applyUpdate()强制小程序重启并使用新版本。在小程序新版本下载完成后(即收到 onUpdateReady 回调)调用。
  • UpdateManager.onUpdateFailed监听小程序更新失败事件。小程序有新版本,客户端主动触发下载(无需开发者触发),下载失败(可能是网络原因等)后回调

猜你喜欢

转载自blog.csdn.net/qq_23073811/article/details/131509118