小程序获取某项权限的通用写法
温馨提示:
errMsg: "openSetting:fail can only be invoked by user TAP gesture."
- wx.openSetting 不能直接在程序中调用,但是可以通过 wx.showModal 拉起。
小程序获取某项权限
- 【相关链接】微信小程序:开放能力/用户信息/授权
- 【相关链接】表单组件/button ,
open-type
:openSetting
- uni -> wx , 有些地方写的是
uni
直接替换为wx
- 可以把
scope.userLocation
替换为其他值,或者封装一下,变成通用的获取权限方式 - 封装时,别忘记,把
"需要您授权获取地理位置权限"
也封装一下,这个是弹窗的提示信息 - 提示: 这里的几个方法 promise 返回的是数组,
arr[0]
有值,就是出错了;arr[1]
才是success时返回的结果值,想要获取的结果值都存放在arr[1]
中。
// (1) uni.getSetting -> (2) uni.authorize -> (3) uni.showModal -> (4) uni.openSetting
//授权获取地理位置权限
async getAuth_userLocation(){
try {
//(1)getSetting
const authSetting = await uni.getSetting();
if (authSetting['scope.userLocation']) {
return true;
} else {
//(2)authorize
const resAuthorize = await uni.authorize({ scope: 'scope.userLocation' })
//resAuthorize[0]:拒绝,resAuthorize[1]:接受;
if (resAuthorize[1]) {
return true;
} else {
//(3)showModal
const resShowModal = await uni.showModal({ title: '授权', content: '需要您授权获取地理位置权限' });
//resShowModal[0]: null, resShowModal[1]: `confirm`,`cancel`都定义在"resShowModal[1]"中
if (resShowModal[1]) {
if (resShowModal[1].confirm) {
//(4)openSetting
const resOpenSetting = await uni.openSetting();
//resOpenSetting[0]: null, resOpenSetting[1]: `authSetting`定义在"resOpenSetting[1]"中
if (resOpenSetting[1]) {
const authSetting = resOpenSetting[1].authSetting;
if (authSetting && authSetting['scope.userLocation']) {
return true;
} else {
return false;
}
} else {
return false;
}
}
if (resShowModal[1].cancel) {
return false;
}
} else {
return false;
}
}
}
} catch (err) {
console.log(err);
return false;
}
},
原来的写法
getCameraAuth(){
const that = this;
// 获取摄像头权限
// (1) uni.getSetting -> (2) uni.authorize -> (3) uni.showModal -> (4) uni.openSetting
uni.getSetting({
success(res) {
const authSetting = res.authSetting;
if (authSetting['scope.camera']) {
// 已经授权
that.is_camera_auth = true;
} else {
// 未授权
uni.authorize({
scope: 'scope.camera',
success(resSuccess) {
// 同意授权
that.is_camera_auth = true;
},fail(resFail) {
console.log("resFail: ", resFail);
// 引导用户授权
uni.showModal({
title: '授权',
content: '需要您授权获取摄像头权限',
success: function (res) {
if (res.confirm) {
uni.openSetting({
success(resOpenSetting) {
// resOpenSetting: {errMsg: "openSetting:ok", authSetting: {scope.camera: false}}
//console.log("resOpenSetting: ", resOpenSetting)
const authSetting = resOpenSetting.authSetting
if (authSetting && authSetting['scope.camera']) {
that.is_camera_auth = true;
} else {
uni.showToast({icon:'none', title: '您拒绝授权小程序获取摄像头权限', duration: 1500});
}
}
});
} else if (res.cancel) {
uni.showToast({icon:'none', title: '您拒绝授权小程序获取摄像头权限', duration: 1500});
}
}
});
}
});
}
}
});
},
- 这是原来的嵌套写法,没有上面的 Promise 版本方便;放在这里作为参照。
2 回复
const sysInfo = await wx.getSystemInfoSync();
const locationEnabled = sysInfo['locationEnabled'];
可以通过 wx.getSystemInfoSync() 获取系统信息,其中 locationEnabled 表示是否开启了定位
我原来是根据 wx.getLocation 抛出异常来判断是否开启了定位的,现在改为使用上面的方式。