typescript - Expo 位置錯誤:未被授權使用背景位置服務
我正在創建一個需要使用者當前位置並且需要實時運行的應用。我使用的是 Expo 的 Location.startLocationUpdatesAsync(),但是我遇到了以下錯誤。app.json 已經配置好了,而且我在手機上也接受了位置權限。有人可以告訴我為什麼會遇到這個錯誤嗎?
app.json
"ios": {
"supportsTablet": true,
"bundleIdentifier": "com.ourtor.ourtorapp",
"buildNumber": "0.0.8",
"infoPlist": { "UIBackgroundModes": [ "location", "fetch" ] }
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#FFFFFF"
},
"permissions": [
"ACCESS_COARSE_LOCATION",
"ACCESS_FINE_LOCATION",
"ACCESS_BACKGROUND_LOCATION"
]
},
map.ts
useEffect( () => {
Location.requestPermissionsAsync().then( async (res) => {
if(res.status === "granted") {
console.log('granted')
await Location.startLocationUpdatesAsync('get-location', {
accuracy: Location.Accuracy.Balanced
})
}
});
}, [])
控制台 安卓
granted
[Unhandled promise rejection: Error: Not authorized to use background location services.]
控制台 iOS
granted
Background Location has not been configured. To enable it, add 'location' to 'UIBackgroundModes' in Info.plist file.
答案#1
你真的需要背景位置嗎?看起來為背景使用配置位置要麻煩得多。位置的配置矩陣很複雜(Android、Apple、模擬器、權限、前景\背景,甚至還有 Android 的應用提交請求)。我建議你一定要仔細閱讀 Expo 的文檔,因為所有這些細節都散落在頁面各處:https://docs.expo.io/versions/latest/sdk/location/#background-location-methods
話雖如此,我在 Android 上應用程式處於前景時獲取位置時也遇到了類似的問題。我必須確保在 Android 應用程式設置中為 Expo Go 開啟了位置。僅此還不夠,還需要調用 Location.getPermissionAsync()(在我的 Apple 設備上不需要)。然後我就能夠毫無問題地使用 Location.watchPositionAsync(...)。
我還想提一下,當你的問題出現時,Expo Go 中的定位功能存在一個較大的問題(當時它仍然是 Expo Client)。你可以查看這個 GitHub 問題了解更多細節:https://github.com/expo/expo/issues/11330。簡單來說,如果你使用的 Expo Go 版本高於 2.18.5,就不應該再看到這個問題了。
答案#2
使用 Expo 權限有更好的方法來做到這一點,欲了解更多資訊請查看 https://docs.expo.io/versions/latest/sdk/permissions/