uniapp检查更新并显示下载进度

uni.request({
	url: "http://2132",  //请求更新地址
	data: '',
	success(res) {
		if (!!res.data) {
			uni.showModal({
				title: '版本更新' + res.data.versionCode,
				content: res.data.description,
				confirmText: "更新",
				showCancel: !res.forceUpdate,
				success: function(e) {
					if (e.confirm) {
						if (plus.os.name.toLowerCase() == 'ios') {
							// 跳转到下载页面
							plus.runtime.openURL(res.data.upgradeUrl)
						} else {
							var dtask = plus.downloader.createDownload(
								res.data.upgradeUrl, {},
								function(d, status) {
									uni.showToast({
										title: '下载完成',
										mask: false,
										duration: 1000
									});
									// 下载完成
									if (status == 200) {
										plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, e => e, function(error) {
											uni.showToast({
												title: '安装失败-01',
												mask: false,
												duration: 1500
											});
										})
									} else {
										uni.showToast({
											title: '更新失败-02',
											mask: false,
											duration: 1500
										});
									}
								});
							 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: '更新失败-03',
								  	mask: false,
								  	duration: 1500
								  });
							  }
						}

					} else {
						//取消
					}
				}
			});
		} else {
			uni.showModal({
						    title: '提示',
						content: '已是最新版本',
						showCancel: false
					});
		}
	},
})
 

猜你喜欢

转载自blog.csdn.net/weixin_36185028/article/details/103126680