使用方法:
函數參數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)
}
})
})
}