用户授权
今天我们来讲解微信小程序之用户授权,首先这个我们得分2种情况:1、弹出授权框用户点击允许 2、弹出授权框用户点击拒绝
第一种情况: 很好处理,这里就不多做介绍,按正常的走就可以了
第二种情况: 如果拒绝之后,你会发现调用了但是不会弹出给用户选择权限的对话框,这才是本篇文章的重点,方法我这里都写好了,大家按照这个去深入理解,注释都写的比较清楚了。
代码如下:
.
.
.
.
.
.
.
授权方法如下
getLocationPermission() {
return new Promise(function (resolve, reject) {
wx.getSetting({
success(res) { // 1、查看所有权限
let status = res.authSetting['scope.userLocation'] // 查看位置权限的状态,此处为初次请求,所以值为undefined
console.log('查看位置权限状态:', status)
if (!status) { // 如果是首次授权(undefined)或者之前拒绝授权(false)就会进入
wx.authorize({ // 2、发起请求用户授权(用户点击了拒绝,之后是调不出获取权限对话框的,就会进入失败fail)
scope: 'scope.userLocation',
success() { // 用户允许了授权
resolve(true)
},
fail(e) {
console.log('用户之前拒绝过', e)
wx.showModal({
title: '是否授权当前位置',
content: '需要获取您的地理位置,请确认授权,否则wifi功能将无法使用',
success: function (res) {
if (res.confirm) {
wx.openSetting({ //3、打开授权设置页面(这个要放在showModal里,不然会失败)
success(data) {
if (data.authSetting["scope.userLocation"] == true) {
wx.showToast({
title: '位置授权成功',
icon: 'success',
duration: 2000,
success() {}
})
} else {
console.log('从授权设置页面返回,用户不给授权')
}
},
fail(e) {
console.log('打开授权设置失败')
wx.showToast({
title: '位置授权失败,不能获取wifi列表',
icon: 'none',
duration: 2000,
success() {}
})
}
})
}
}
})
}
})
} else {
console.log('用户之前授权过')
resolve(true)
}
}
})
})
}
调用
// 获取用户位置权限
that.getLocationPermission().then(res => {
if (res) {
}
})