代码仓库:https://gitee.com/DerekAndroid/miniProgramAgen/tree/master/pages/authSetting
效果:
wxml:
<button bindtap="checkScopeCamera">申请获取相机权限</button>
<button bindtap="checkScopeCamera">申请获取相机权限-同步函数方式</button>
<button bindtap="checkScope">同时申请获取麦克风、相机权限</button>
js:
// pages/authSetting/authSetting.js
Page({data: {},onLoad: function (options) {},onShow: function () {},getSettingRecord(options = { scope: 'scope.record', content: '请前往设置页打开麦克风' }) {var self = this;return new Promise((resolve, reject) => {wx.getSetting({success: (res) => {let auth = res.authSetting[options.scope]console.warn('scope.record=', auth, typeof auth)if (auth === true) { // 用户已经同意授权resolve(true)}else if (auth === undefined) {// 首次发起授权wx.authorize({scope: options.scope,success() {resolve(true)},fail(res) {}})}else if (auth === false) { // 非首次发起授权,用户拒绝过 => 弹出提示对话框wx.showModal({title: '授权提示',content: options.content,success: (tipRes) => {if (tipRes.confirm) {wx.openSetting({success: (settingRes) => {if (settingRes.authSetting[options.scope]) {resolve(true)}console.warn('settingRes', settingRes)},})}}})}},})})},//申请获取相机权限checkScopeCamera() {var options = { scope: 'scope.camera', content: '请前往设置页打开摄像头' }var promise2 = this.getSettingRecord(options)promise2.then((res) => {if (res) {wx.showToast({title: '相机权限已获取',})}})},//申请获取相机权限-同步函数方式async checkScopeCameraAsync() {var options = { scope: 'scope.camera', content: '请前往设置页打开摄像头' }var flag = await this.getSettingRecord(options)console.warn('flag', flag)if (flag) {wx.showToast({title: '相机权限已获取',})}},//检测权限:同时申请获取麦克风、相机权限checkScope() {return new Promise((resolve, reject) => {var promise1 = this.getSettingRecord()var options = { scope: 'scope.camera', content: '请前往设置页打开摄像头' }var promise2 = this.getSettingRecord(options)Promise.all([promise1, promise2]).then(res => {console.warn('Promise.all', res);if (res[0] && res[1]) {console.warn('获取权限成功')wx.showToast({title: '获取麦克风、相机权限成功',icon:'none'})resolve();}})})},})
...