我們在開發(fā)微信小程序時都會需要用到一些用戶權(quán)限,如:錄像頭烘苹、錄音筋量、保存到相冊等等權(quán)限
以下是我封裝的js,提供給大家使用
checkAnth.js
export?default?class?checkAnth?{
??constructor() {
??}
??//?初始化授權(quán)獲取(授權(quán)wxSetting,授權(quán)名稱)
??initcheckAuth(authName,?authtype)?{
????var?_that=this
????this.checkAuth().then(setRes?=>?{
??????if?(!setRes[authName])?{
????????wx.authorize({
??????????scope:?authName,
??????????success(authRes)?{
????????????console.log(authRes,?authtype);
??????????},
??????????fail(authErr)?{
????????????_that.checkAuth(true,?authName,?authtype)
??????????}
????????})
??????}
????})
??}
??//?檢測授權(quán)和提示
??checkAuth(showModel?=?false,?authName,?authtype)?{
????return?new?Promise((resolve,?reject)?=>?{
??????wx.getSetting({
????????success(res)?{
??????????if?(!res.authSetting[authName])?{
????????????if?(showModel)?{
??????????????wx.showModal({
????????????????title:?'授權(quán)提示',
????????????????content:?`需要您的${authtype}`,
????????????????confirmText:?'去開啟',
????????????????confirmColor:?'#FE5250',
????????????????success(modelRes)?{
??????????????????if?(modelRes.confirm)?{
????????????????????wx.openSetting()?//?打開授權(quán)管理頁面
??????????????????}?else?{
????????????????????wx.showToast({?title:?`請前往開啟手機${authtype}權(quán)限~`,?icon:?'none',?duration:?3000?})
??????????????????}
????????????????}
??????????????})
????????????}
????????????resolve({?authName:?false?})
??????????}?else?{
????????????resolve({?authName:?true?})
??????????}
????????},
????????fail:?err?=>?{
??????????wx.showToast({?title:?`請檢測手機${authtype}是否開啟,重新進入本頁面~`,?icon:?'none',?duration:?3000?})
????????}
??????})
????})
??}
}
在頁面中引入
import?anthUtils?from?'../../../../utils/checkAnth.js';
const?anth?=?new?anthUtils();
?anth.initcheckAuth('scope.camera',?'攝像頭')伪很;//調(diào)用即可