微信小程序,用户拒绝授权后重新授权;uni-app小程序,用户拒绝授权后点击无效;重新进入后拉起位置授权框;
问题:当用户第一次进入小程序,点击授权按钮后,点了拒绝,再次点击不会出现授权页面,只有再次进入小程序的时候,才会出发请求授权 。案例: 假如我们获取微信位置,第一次点击的时候弹起授权,用户点击的拒绝,当用户再次点击的时候,如何继续弹出授权?实现步骤:1、首先我们需要判断用户是否开启授权获取地理位置(wx.getSetting)2、如果已经授权(,直接获取位置(wx.getLocation)3、如果
问题:当用户第一次进入小程序,点击授权按钮后,点了拒绝,再次点击不会出现授权页面,只有再次进入小程序的时候,才会出发请求授权 。
案例: 假如我们获取微信位置,第一次点击的时候弹起授权,用户点击的拒绝,当用户再次点击的时候,如何继续弹出授权?
实现步骤:
1、首先我们需要判断用户是否开启授权获取地理位置(wx.getSetting)
2、如果已经授权,直接获取位置(wx.getLocation)
3、如果没有授权,弹出授权框(wx.authorize)
— 3.1 点击确定之后,会走success,获取位置
— 3.2 点击拒绝之后,会走fail,这是会发现当我们再次点击的时候会发现已经弹不出授权框了,
所以我们要在fail里面做一下处理,需要让他弹出授权框
4、fail处理:
由于wx.openSetting必须通过按钮触发,所以我们当用户拒绝的时候添加一个弹出框(wx.showModal)
— 4.1 当用户点击弹框的确定按钮的时候,调用wx.openSetting,微信会自动再次拉起位置授权框;
— 4.2 当用户点击弹框的取消按钮的时候,就提示即可。
代码如下,可直接复制(前提是你在manifest.json配置好了permission权限);未配置看这篇
<template>
<view>
<button type="" @click="getLocation">获取位置</button>
<view>经度:{{x}}</view>
<view>纬度:{{y}}</view>
</view>
</template>
<script>
export default {
data () {
return {
x: 0,
y: 0
}
},
methods: {
getLocation () {
let that = this
// 获取用户是否开启 授权获取当前的地理位置、速度的权限。
uni.getSetting({
success (res) {
console.log(res)
// 如果没有授权
if (!res.authSetting['scope.userLocation']) {
// 则拉起授权窗口
uni.authorize({
scope: 'scope.userLocation',
success () {
//点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
uni.getLocation({
type: 'wgs84',
success: function (res) {
that.x = res.longitude
that.y = res.latitude
console.log(res)
console.log('当前位置的经度:' + res.longitude)
console.log('当前位置的纬度:' + res.latitude)
uni.showToast({
title: '当前位置的经纬度:' + res.longitude + ',' + res.latitude,
icon: 'success',
mask: true
})
}, fail (error) {
console.log('失败', error)
}
})
},
fail (error) {
//点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
console.log('拒绝授权', error)
uni.showModal({
title: '提示',
content: '若点击不授权,将无法使用位置功能',
cancelText: '不授权',
cancelColor: '#999',
confirmText: '授权',
confirmColor: '#f94218',
success (res) {
console.log(res)
if (res.confirm) {
// 选择弹框内授权
uni.openSetting({
success (res) {
console.log(res.authSetting)
}
})
} else if (res.cancel) {
// 选择弹框内 不授权
console.log('用户点击不授权')
}
}
})
}
})
} else {
// 有权限则直接获取
uni.getLocation({
type: 'wgs84',
success: function (res) {
that.x = res.longitude
that.y = res.latitude
console.log(res)
console.log('当前位置的经度:' + res.longitude)
console.log('当前位置的纬度:' + res.latitude)
uni.showToast({
title: '当前位置的经纬度:' + res.longitude + ',' + res.latitude,
icon: 'success',
mask: true
})
}, fail (error) {
uni.showToast({
title: '请勿频繁调用!',
icon: 'none',
})
console.log('失败', error)
}
})
}
}
})
}
},
}
</script>
<style>
</style>
更多推荐
所有评论(0)