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、苹果、模拟器、权限、前台\后台,甚至 Android 应用提交请求)。我建议你确保已经彻底阅读了 Expo 的文档,因为所有这些细节都分散在页面中:https://docs.expo.io/versions/latest/sdk/location/#background-location-methods
话虽如此,我在 Android 上的应用处于前台时获取位置时也遇到了类似的问题。我必须确保在 Android 应用设置中为 Expo Go 打开了位置权限。不过,仅此还不够,还需要调用 Location.getPermissionAsync()(在我的苹果设备上不需要)。然后我就可以毫无问题地使用 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/