需求
小程序上如果需要一些定位功能,那么我們需要提前獲取定位權限。我們頁面的所有功能后續(xù)都需要在用戶同意的前提下進行,所以一旦用戶點了拒絕,我們應該給予提示,并讓用于修改為允許。
實現(xiàn)
1.打開手機GPS
經過測試發(fā)現(xiàn)即使手機GPS沒有打開,小程序依舊可以獲取定位信息。
const { locationEnabled } = uni.getSystemInfoSync()
if (!locationEnabled) {
uni.showToast({
title: '該功能需要手機定位,請打開手機定位后重新進入!',
})
return
}
2.獲取小程序定位權限
- 首先我們檢查用戶是否開啟了該權限
因為抽離成了公共方法,所以會復雜一些,主要就是調用//傳一個權限key,則返回true,false判斷是否有該權限 //傳一個權限key的數(shù)組,返回沒有打開的權限列表 export async function authIsPass (authValue: string | string[]) { try { const res = await new Promise((resolve, reject) => { uni.getSetting({ success: (res) => { resolve(res) }, fail: (err) => { reject(err) }, }) }) const { authSetting }: any = res if (typeof authValue === 'string') { if (authSetting[authValue]) { return true } else { return false } } if (Array.isArray(authValue)) { let noPassList: string[] = authValue.filter((key: string) => !authSetting[key]) if (noPassList.length > 0) { return noPassList } else { return [] } } } catch (err) { return false } }
uni.getSetting
獲取到所有的設置權限,然后判斷自己所需要的權限是否開啟。
3.進行權限獲取
uni.authorize({
scope: 'scope.userLocation',
fail: (res) => {
uni.showModal({
title: '使用該功能必須允許位置服務,是否重新授權?',
showCancel: false,
success: ({ confirm }) => {
if (confirm) {
uni.openSetting({
success() {
//重新獲取權限并判斷
console.log('開啟權限成功')
},
fail() {
console.log('開啟權限失敗')
},
})
}
},
})
},
success: () => {
//重新獲取權限并判斷
},
})
上面代碼主要依靠uni.showModal
方法進行權限獲取,如果你之前拒絕過該權限,則直接走fail
回調,如果同意則走success
回調。拒絕之前使用uni.showModal
進行權限提示,并且在確定按鈕綁定uni.openSetting
方法重新進行權限設置。文章來源:http://www.zghlxwxcb.cn/news/detail-853448.html
完整邏輯
const setLocationAuth = async () => {
const { locationEnabled } = uni.getSystemInfoSync()
if (!locationEnabled) {
uni.showToast({
title: '該功能需要手機定位,請打開手機定位后重新進入!',
})
return
}
// 判斷用戶是否獲取定位權限
//authIsPass方法就是上面步驟2的方法
const flag = await authIsPass('scope.userLocation')
if (!flag) {
uni.authorize({
scope: 'scope.userLocation',
fail: (res) => {
uni.showModal({
title: '使用該功能必須允許位置服務,是否重新授權?',
showCancel: false,
success: ({ confirm }) => {
if (confirm) {
uni.openSetting({
success() {
setLocationAuth()
console.log('開啟權限成功')
},
fail() {
console.log('開啟權限失敗')
},
})
}
},
})
},
success: () => {
setLocationAuth()
},
})
return
}
//獲取到定位權限后的操作
}
setLocationAuth()
上面方法,是在vue3 + ts的環(huán)境執(zhí)行的。進入頁面就會立即執(zhí)行setLocationAuth
方法,然后走獲取權限的邏輯。如果用戶點擊拒絕則會彈出提醒,用戶點擊確定按鈕后會跳到權限設置頁面進行重新設置。無論他選擇了允許還是不允許,重新回到頁面都會重新執(zhí)行setLocationAuth
方法,再次進行判斷。文章來源地址http://www.zghlxwxcb.cn/news/detail-853448.html
到了這里,關于uniapp小程序獲取位置權限(不允許拒絕)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!