/**
*
* @param {*} authKey 权限的 scope
* @param {*} callback 回调函数
*/
export default function userAuthorize(authKey, callback) {
uni.getSetting({
success: (res) => {
if(res.authSetting.hasOwnProperty(authKey)) {
if(res.authSetting[authKey]) {
callback(true)
}else {
// 因为现在openSetting无法直接调用了,要通过触发tap,所以如果权限是在页面加载时调用的那么这里需要调整一下,手动提示用户调用openSetting
uni.openSetting();
callback(false)
}
}else {
uni.authorize({
scope: authKey,
success: () => {
callback(true)
},fail() {
callback(false)
}
})
}
}
})
}
因为 uni.authorize API只会调用一次授权弹出层,所以先用uni.getSetting API获取authSetting 用户授权结果
如果key也就是当前 scope存在并且为true,说明已经授权,如果为false调用uni.openSetting API手动开启权限, 这里在没找到key的情况下就说明当前是第一次授权那么会调用uni.authorize弹出授权框。只有调用过uni.authorize API后uni.getSetting的authSetting属性中才会存在当前scope
导入使用:
userAuthorize('scope.writePhotosAlbum', (state) => {
// state为真说明已授权
if(!state) return
.....
})