获取位置权限用户拒绝授权后重新引导用户授权
在微信小程序开发中,有很多场景需要强依赖用户位置信息,但获取位置信息必须要显式的经过用户授权,然而很多用户对授权比较敏感,可能会点击拒绝,本文介绍如何用户拒绝授权后重新引导用户授权
第一步
请求用户进行位置信息的授权,使用uni.authorize实现。
- 如果用户之前已经授权过,那么会直接回调success。
- 如果用户是第一次进入,则会弹出提示框提醒用户授权
a. 如果用户点击允许,则会执行获取用户位置信息的逻辑
b. 如果用户点击拒绝,由于场景强依赖位置,必须要用户授权,此时弹出提示框引导用户授权(反复弹框,直到授权)
代码如下
// 获取位置权限
getLocationDetail(){
let that = this
return new Promise((resolve,reject)=>{
// 请求用户授权,第一次进入会有位置授权的提示
uni.authorize({
scope: 'scope.userLocation',
success() {
console.log("用户成功授权位置信息")
that.getUserLocation()
},
fail() {
console.log("用户拒绝授权位置信息,再次提示用户授权")
that.showRefuseLocationPermission()
}
})
})
},
第二步
如果用户点击允许的情况下,执行获取用户位置信息的逻辑,代码如下
// 获取位置信息--用户授权后执行
getUserLocation() {
const that = this;
uni.getLocation({
type: 'gcj02',
success(res) {
console.log("获取用户位置成功")
that.location = res
// 解析位置信息等操作。。
resolve(res)
},
fail(res) {
console.log('获取用户位置失败,其他问题')
reject(res)
},
})
},
第三步
如果用户点击拒绝,必须要明显的提示用户进行授权,弹出提示框引导用户进入设置页面授权,如果用户依然拒绝,则反复弹框,直到用户授权。代码如下:
// 用户拒绝授权的展示
showRefuseLocationPermission() {
const that = this;
wx.showModal({
title: "提示",
content: "需要获取用户位置权限",
confirmText: "前往设置",
showCancel: false,
success(res) {
if (res.confirm) {
uni.openSetting({
success: (res) => {
console.log("打开设置成功", res);
if (res.authSetting['scope.userLocation']) {
console.log('成功授权userLocation')
that.getUserLocation()
} else {
console.log('用户未授权userLocation')
// 递归调用本函数,(函数套函数)
that.showRefuseLocationPermission()
}
},
fail: (err) => {
console.log("打开设置失败", err)
}
})
}
}
})
},
整体流程结束
完整代码
// 获取位置权限
getLocationDetail() {
let that = this
return new Promise((resolve, reject) = >{
// 请求用户授权,会有位置授权的提示
uni.authorize({
scope: 'scope.userLocation',
success() {
console.log("用户授权位置信息")
that.getUserLocation()
},
fail() {
that.showRefuseLocationPermission()
}
})
})
},
// 获取位置信息--用户授权后执行
getUserLocation() {
const that = this;
uni.getLocation({
type: 'gcj02',
success(res) {
console.log("获取用户位置成功")
that.location = res
// 解析位置信息等操作。。
resolve(res)
},
fail(res) {
console.log('获取用户位置失败,其他问题')
reject(res)
},
})
},
// 用户拒绝授权的展示
showRefuseLocationPermission() {
const that = this;
wx.showModal({
title: "提示",
content: "需要获取用户位置权限",
confirmText: "前往设置",
showCancel: false,
success(res) {
if (res.confirm) {
uni.openSetting({
success: (res) = >{
console.log("打开设置成功", res);
if (res.authSetting['scope.userLocation']) {
console.log('成功授权userLocation')
that.getUserLocation()
} else {
console.log('用户未授权userLocation')
// 递归调用本函数,(函数套函数)
that.showRefuseLocationPermission()
}
},
fail: (err) = >{
console.log("打开设置失败", err)
}
})
}
}
})
},