咱们在开发小程序时,有些操做必须让用户受权。好比咱们获取用户位置,须要用户受权位置信息。受权操做咱们须要给用户弹窗提示,在用户禁用某些权限时,又要引导用户去设置页开启相应权限。咱们这里就以获取经纬度为例,来带你们学会友好的引导用户受权。git
//校验位置权限是否打开
checkLocation() {
let that = this;
//选择位置,须要用户受权
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success() {
wx.showToast({ //这里提示失败缘由
title: '受权成功!',
duration: 1500
})
},
fail() {
that.showSettingToast('须要受权位置信息');
}
})
}
}
})
},
复制代码
// 打开权限设置页提示框
showSettingToast: function (e) {
wx.showModal({
title: '提示!',
confirmText: '去设置',
showCancel: false,
content: e,
success: function (res) {
if (res.confirm) {
wx.navigateTo({
url: '../setting/setting',
})
}
}
})
},
复制代码
因为去设置页,须要用户手动触发,这里咱们就用一个setting.wxml页做为过过渡页。 小程序
//index.js
Page({
getLocation() {
this.checkLocation();
let that = this;
wx.chooseLocation({
success: function(res) {
var latitude = res.latitude
var longitude = res.longitude;
that.setData({
address: "经纬度:" + longitude + ", " + latitude,
})
}
});
},
//校验位置权限是否打开
checkLocation() {
let that = this;
//选择位置,须要用户受权
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success() {
wx.showToast({ //这里提示失败缘由
title: '受权成功!',
duration: 1500
})
},
fail() {
that.showSettingToast('须要受权位置信息');
}
})
}
}
})
},
// 打开权限设置页提示框
showSettingToast: function (e) {
wx.showModal({
title: '提示!',
confirmText: '去设置',
showCancel: false,
content: e,
success: function (res) {
if (res.confirm) {
wx.navigateTo({
url: '../setting/setting',
})
}
}
})
},
})
复制代码
by 年糕妈妈qclbash