最近也是写了好几个unit-app的小程序,把用到的几个方法封装一下,提供给需要的小伙伴;
获取权限
export function IsOpenPower (a = "scope.userLocation") {
return new Promise((resolve, reject) => {
uni.getSetting({ // 判断是否有当前权限
success(res) {
if (!res.authSetting[a]) { // 没有当前权限
uni.authorize({
scope: a,
success() { // 允许授权
resolve();
},
fail() { // 拒绝授权
uni.showModal({ // 再次申请
title: '提示',
content: '你已经取消过授权,需设置授权权限',
confirmText: '设置',
success: function(res) {
if (res.confirm) {
uni.openSetting({ // 调用小程序设置
success(res) {
if (res.authSetting[a]) {
resolve();
} else {
reject('设置权限失败');
}
},
fail() {
reject('调用设置权限失败');
}
})
} else if (res.cancel) {
reject('取消了授权');
}
}
});
}
})
} else { // 含有定位权限
resolve();
}
},
fail() {
reject('获取权限失败');
}
});
})
}
扫码
export function ScanCode(scanType = ['qrCode']) {
return new Promise((resolve, reject) => {
uni.scanCode({
onlyFromCamera: true,
scanType: scanType,
success: function (res) { // res.scanType: '条码类型', res.result: '条码内容'
res.result = JSON.parse(res.result);
resolve(res);
},
fail: function(e) {
ShowToast('扫码失败');
reject();
}
});
});
}
获取定位
export function GetLocation (type = 'gcj02') {
return new Promise((resolve, reject) => {
uni.getLocation({
type: 'gcj02',
success (res) { // longitude latitude
resolve(res);
},
fail(res) {
uni.showModal({
title: '提示',
content: '定位获取失败,请检查网络是否连接,或检查软件是否开启定位功能',
confirmText: '确定',
});
reject();
}
});
});
}
弹窗
export function ShowToast(title = '', icon = 'none', position = 'center') {
uni.showToast({title, icon, position, duration: 1500});
}
检查版本
// 使用在App.vue中 onShow中调用
// 检查小程序版本
export function UpdateApp() {
const updateManager = uni.getUpdateManager();
updateManager.onCheckForUpdate(function (res) {
// 请求完新版本信息的回调
console.log(res.hasUpdate);
});
updateManager.onUpdateReady(function (res) {
uni.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate();
}
}
});
});
updateManager.onUpdateFailed(function (res) {
// 新的版本下载失败
ShowToast('新版本下载失败')
});
}: