uniapp小程序授权统一处理
1.使用
1.将工具代码引入到utils中
const authorize = (scope, isOne = false, isMust = false) => {if (!scope || !authorizeObj[scope]) {return console.error('请传输需要获取权限的 scope,详见','https://uniapp.dcloud.net.cn/api/other/authorize.html#scope-%E5%88%97%E8%A1%A8')}return new Promise(async (resolve, reject) => {let hasAuthorize = await getAuthorize(scope)if (hasAuthorize) {resolve()} else {uni.authorize({scope: `scope.${scope}`,success: (authorizeRes) => {resolve()},fail: (authorizeErr) => {if (!isOne) {showModal(resolve, reject, scope, isMust)} else {reject()}}})}})
}
const showModal = (resolve, reject, scope, isMust) => {uni.showModal({title: '温馨提示',content: `获取${authorizeObj[scope]}失败,是否进入设置页开启您的权限?`,success: (showModalRes) => {if (showModalRes.confirm) {uni.openSetting({success: (openSettingRes) => {if (openSettingRes.authSetting[`scope.${scope}`]) {resolve()} else {if (isMust) {showModal(resolve, reject, scope, isMust)} else {reject()}}}});} else {reject()}}})
}//查看是否授权
const getAuthorize = (scope) => {return new Promise((resolve, reject) => {uni.getSetting({success(res) {resolve(res.authSetting[`scope.${scope}`])}})})
}
let authorizeObj = {'userLocation': '精确地理位置','userFuzzyLocation': '模糊地理位置','userLocationBackground': '后台定位','record': '麦克风权限','camera': '摄像头权限','bluetooth': '蓝牙权限','writePhotosAlbum': '添加到相册权限','addPhoneContact': '添加到联系人权限','addPhoneCalendar': '添加到日历权限','werun': '微信运动步数权限','address': '通讯地址权限','invoiceTitle': '发票抬头权限','invoice': '获取发票权限','userInfo': '用户信息权限'
}export default authorize
2.打开main.js 将方法挂载到全局
//授权方法全局挂载
import authorize from '@/utils/authorize.js'
Vue.prototype.$authorize = authorize
3.页面中使用
this.$authorize('writePhotosAlbum',true).then(()=>{//成功授权后相应逻辑
}).catch(()=>{//拒绝授权后相应逻辑
}).finally(() => {//无论授权成功或者失败都执行的逻辑
});
2.参数详解
const authorize = (scope, isOne = false, isMust = false) => {}
参数名 | 默认值 | 参考值 | 备注 |
---|---|---|---|
scope | 无 | userLocation、userFuzzyLocation… | 权限标识目前支持参数如下 |
isOne | false | true、false | 授权是否只能一次(是否支持弹窗跳转设置页) |
isMust | false | true、false | 是否必须授权(如果必须授权,在设置页如果没有开启权限返回页面还会弹提示) |
scope :权限标识 参考 文档
目前支持参数
'userLocation': '精确地理位置',
'userFuzzyLocation': '模糊地理位置',
'userLocationBackground': '后台定位',
'record': '麦克风权限',
'camera': '摄像头权限',
'bluetooth': '蓝牙权限',
'writePhotosAlbum': '添加到相册权限',
'addPhoneContact': '添加到联系人权限',
'addPhoneCalendar': '添加到日历权限',
'werun': '微信运动步数权限',
'address': '通讯地址权限',
'invoiceTitle': '发票抬头权限',
'invoice': '获取发票权限',
'userInfo': '用户信息权限'
isOne :是否只弹一次授权 默认不是只弹一次
isMust :是否强制授权 true强制授权 false不强制授权
亲测好用