使用方法:
函数参数interfaceName指的是小程序的接口名称,如wx.getLocation
,interfaceName指的就是getLocation
,当获取权限成功时通过Promise resolve(res)
返回,res为对应接口的返回值(获取值可能存在失败情况,需要自己判断),而无权获取信息时通过Promise reject(r)
返回,可以做后续页面显示。
function getInterfaceInfo(interfaceName) {
const authorizationMap = {
'getUserInfo': 'scope.userInfo',
'getLocation': 'scope.userLocation',
'chooseLocation': 'scope.userLocation',
'chooseAddress': 'scope.address',
'chooseInvoiceTitle': 'scope.invoiceTitle',
'chooseInvoice': 'scope.invoice',
'getWeRunData': 'scope.werun',
'startRecord': 'scope.record',
'saveImageToPhotosAlbum': 'scope.writePhotosAlbum',
'saveVideoToPhotosAlbum': 'scope.writePhotosAlbum',
'camera': 'scope.camera'
}
return new Promise((resolve, reject) => {
const scopeName = authorizationMap[interfaceName]
uni.getSetting({
success: (res) => {
console.log(`get user ${scopeName} setting:`, res)
if (scopeName in res.authSetting) {
// 判断用户是否已经有权限
if (res.authSetting[scopeName]) {
console.log('authorize result:', res)
uni[interfaceName]({
success: (res) => {
console.log('get user setting data success:', res)
resolve(res)
},
fail: (r) => {
console.log('get user setting data fail:', res)
resolve(r)
}
})
} else {
reject(res)
}
} else {
uni.authorize({
scope: scopeName,
success: (res) => {
console.log('authorize result:', res)
uni[interfaceName]({
success: (res) => {
console.log('get user setting data success:', res)
resolve(res)
},
fail: (r) => {
console.log('get user setting data fail:', res)
resolve(r)
}
})
},
fail: (r) => {
console.log('fail:', r)
reject(r)
}
})
}
},
fail: (r) => {
reject(r)
}
})
})
}