微信小程序授權狀態處理,
/**
* 判斷對應的name是否授權
* name{String} 權限scope字符串
*/
const authSetting = (name) => {
return new Promise((resolve, reject) => {
wx.getSetting({
success: res => {
if (res.authSetting[name] === undefined){
// 爲undefined時,第一次進入,拋出成功
resolve(0)
} else if (res.authSetting[name] === true){
// 爲true時,則表示用戶已經同意授權,拋出成功
resolve(1)
} else if (res.authSetting[name] === false){
// 爲flase時,則表示用戶拒絕授權,當再次進來時,提醒用戶授權
wx.showModal({
title: '溫馨提示',
content: '您需要授權後,才能使用相應功能,是否重新授權',
confirmColor: '#ff2d4a',
success(res) {
if (res.confirm) {
// 如果用戶點了確定,就打開 設置 界面
wx.openSetting({
success(res) {
// 不管是否開啓授權,都執行success
// 再對相應的name進行判斷,是否開啓了授權,如是則返回成功
if (res.authSetting[name] === true) {
resolve(1)
}
}
})
} else if (res.cancel) {
// 用戶點擊取消,不需要做任何處理
}
}
})
}
}
})
})
}
用法:
authSetting('scope.userLocation').then((type) => {
wx.getLocation({
type: 'gcj02',
success: res => {
console.log(res)
}
})
})