UNIAPP官方给出了一个wgt热更新功能,通过热更新我们可以进行小部分功能的更新热更新官方地址

通过官方给出的教程进行前端搭建

export const updateWgt = () => {
	return new Promise(async (reslove, reject) => {
		plus.runtime.getProperty(plus.runtime.appid, async (widgetInfo) => {
			let res = await fetch(config.wgt_url, widgetInfo);
			const {
				data,
				err,
				msg
			} = res;
			if (!err) {
				const {
					update,
					wgtUrl
				} = data;
				if (update && wgtUrl) {
					uni.showLoading({
						title: '正在更新,请稍后',
						mask: true
					});
					/* 下载软件 */
					const filePath = await downloadFile(wgtUrl);
					uni.hideLoading();
					plus.runtime.install(
						filePath, {
							force: false
						},
						() => {
							/* 重新启动APP资源 */
							plus.runtime.restart()
						},
						(e) => {
							console.log(e);
							/* 更新失败做的操作 */
						}
					);
				}
			} else {
				/* 不用更新做的操作 */
			}
		});
	});

}
// 下载文件
export const downloadFile = (url) => new Promise((resolve) => {
	let res = {
		err: true,
		msg: '下载失败!',
		data: ''
	};
	uni.downloadFile({
		url,
		header: {
			'Account-Token': getStorageSync('token')
		},
		success: ({
			statusCode,
			tempFilePath
		}) => {
			if (statusCode === 200) {
				res = {
					err: false,
					msg: '下载成功~',
					data: tempFilePath
				}
			}
			resolve(res);
		},
		fail: () => resolve(res)
	})
})

 之前搭建没出现过  后来软件会出现这样一个

或者

这样的错误 这个是因为wgt文件名字在手机上重复了  为了避免这个错误,保证保存路径下的wgt名称唯一,可每次下载都创建一个名称唯一的文件夹来储存,避免重复。如用当前长整数类型的时间值作为文件名。

plus.downloader.createDownload(
	wgtUrl, {
		filename: '_doc/update/' + widgetInfo.name + '/' + new Date().getTime() + '/'
	},
	function(res, code) {

	}
).start();

通过这个来实现唯一性

完整的代码如下

export const updateWgt = () => {
	return new Promise(async (reslove, reject) => {
		plus.runtime.getProperty(plus.runtime.appid, async (widgetInfo) => {
			let res = await fetch(config.wgt_url, widgetInfo);
			const {
				data,
				err,
				msg
			} = res;
			if (!err) {
				const {
					update,
					wgtUrl
				} = data;
				if (update && wgtUrl) {
					uni.showLoading({
						title: '正在更新,请稍后',
						mask: true
					});
					/* 下载软件 */
					plus.downloader.createDownload(
						wgtUrl, {
							filename: '_doc/update/' + widgetInfo.name + '/' + new Date().getTime() + '/'
						},
						function(res, code) {
							uni.hideLoading();
							let filePath = res.filename;
							plus.runtime.install(
								filePath, {
									force: false
								},
								(res) => {
									/* 重新启动APP资源 */
									plus.runtime.restart()
								},
								(e) => {
									console.log(e);
									/* 更新失败做的操作 */
								}
							);
						}
					).start();
					uni.hideLoading();
				}
			} else {
				/* 不用更新做的操作 */
			}
		});
	});

}

 

就可以更新成功了 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐