使用方法
// 引入
import {
authorize
} from '@/path/to/xx.js'
// 使用
authorize({
scope: 'scope.userLocation',
showModal: true,
authName: '获取位置信息',
success: () => {
console.log('授权成功')
uni.getLocation({
isHighAccuracy: true,
success: res => {
console.log(res);
},
fail: (err) => {
console.log(err.errMsg);
}
})
},
fail: err => {
console.error('authorize.err: ',err);
uni.showToast({
title: '授权失败',
icon: 'error',
mask: true
})
}
})
关键代码
写入工具库或者相关位置
/**
* 权限获取流程
* @param scope 权限英文名称
* @param success 授权成功的回调
* @param fail 授权失败的回调
* @param showModal 授权失败是否展示对话框提示
* @param authName 授权失败是否展示对话框提示展示的授权名称
* // 例子:开启用户的相册权限
authorize({
scope: 'writePhotosAlbum',
showModal: true,
authName: '保存图片到相册',
success () {
console.log('授权成功')
},
})
*/
export async function authorize(options) {
const {
scope,
success,
fail,
showModal = false,
authName = '',
} = options
try {
const scopeName = `scope.${ scope }`
const auth = await uni.getSetting()
console.log('auth', auth.authSetting[scopeName])
if (!auth.authSetting[scopeName]) {
uni.authorize({
scope: scopeName
}).then((res) => {
console.log('uni.authorize.res: ', res);
if (res.errMsg === 'authorize:ok' && success) success()
}, (err) => {
console.log('uni.authorize.err: ', err);
if (showModal && authName) {
uni.showModal({
title: '授权提示',
content: `您拒绝了${ authName }权限,是否打开设置去授权?`,
}).then((res) => {
if (res.confirm) {
uni.openSetting().then((res2) => {
if (res2.authSetting[scopeName] && success) {
success()
} else if (fail) {
fail()
}
})
} else {
fail && fail()
}
}).catch((res) => {
fail && fail(res)
})
} else {
fail && fail()
}
})
} else {
success && success()
}
} catch (err) {
fail && fail(err)
}
}