咱們在開發小程序時,有些操做必須讓用戶受權。好比咱們獲取用戶位置,須要用戶受權位置信息。受權操做咱們須要給用戶彈窗提示,在用戶禁用某些權限時,又要引導用戶去設置頁開啓相應權限。咱們這裏就以獲取經緯度爲例,來帶你們學會友好的引導用戶受權。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