当前位置: 代码迷 >> 综合 >> uniapp--热更新代码
  详细解决方案

uniapp--热更新代码

热度:49   发布时间:2023-11-19 11:47:08.0
  1. 第一步通过ajax请求后端的wgt文件,这个文件是可以通过HBUILDX生成的更新包
  2. 第二步官网有给了一个前端的更新代码,不过会出现一个错误 unexpected EOF,所以我们用另一个写法
    plus.runtime.getProperty(plus.runtime.appid, function(info) {// ajax请求,这里就不写了,这里模拟一个数据,通过Promis方式,或者回调,这里看你们项目的需求,请求回来数据就可以了let res = {msg : '请求成功',err : false,data : {upload : true,wgtUrl : '服务器存放的地址'},code : 200}// 这里是请求成功后的回调处理const {data,msg,code} = res;if (code == 200) {const {wgtUrl,update} = data;if (update && wgtUrl) {/* 添加下载任务 */var dtask = plus.downloader.createDownload(wgtUrl, {filename: '_doc/update/' + info.name + '/' + new Date().getTime() + '/'},(res, code) => {plus.runtime.install(res.filename, {force: false},(res) => {uni.hideLoading();plus.runtime.restart();},(e) => {uni.hideLoading();});});try {/* 监听下载进度 */dtask.start(); // 开启下载的任务var prg = 0;var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象 dtask.addEventListener('statechanged', function(task,status) {// 给下载任务设置一个监听 并根据状态  做操作switch (task.state) {case 1:showLoading.setTitle("正在下载");break;case 2:showLoading.setTitle("已连接到服务器");break;case 3:prg = parseInt((parseFloat(task.downloadedSize) /parseFloat(task.totalSize)) *100);showLoading.setTitle("  正在下载" + prg + "%  ");break;case 4:plus.nativeUI.closeWaiting();//下载完成break;}});} catch (err) {plus.nativeUI.closeWaiting();uni.showToast({title: '更新失败',mask: false,duration: 1500});}}}});

     

uniapp的更新回调写法 

const dtask = uni.downloadFile({url: wgtUrl,success: (downloadResult) => {console.log(downloadResult);if (downloadResult.statusCode === 200) {plus.runtime.install(downloadResult.tempFilePath, {force: false}, function(res) {plus.runtime.restart();}, function(e) {uni.showToast({title: '更新失败',mask: false,duration: 1500,icon: 'none'});uni.switchTab({url: '/pages/index/index'});});}}});try {var prg = 0;var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象 dtask.onProgressUpdate((res) => {prg = res.progress;showLoading.setTitle("  正在下载" + prg + "%  ");if (prg >= 100) {plus.nativeUI.closeWaiting();}});} catch (err) {plus.nativeUI.closeWaiting();uni.showToast({title: '更新失败',mask: false,duration: 1500});}

具体的代码见上图,给用户添加一个下载的提示,为了用户体验,这里我们再给用户添加上一个进度条,增加产品体验,让用户知道下载的进度,而不是误以为死机