我正在制作一个应用程序,我必须知道该位置是否有效,而不是缓存和当前。
这是一个显示与您近距离的应用程序(使用数据库和其他内容(
每10秒我从网络获取数据,并在表观视图中显示新数据。
假设我在商店附近,并且该应用显示"您靠近商店"
我关闭应用程序,回家,当我打开应用程序时,它仍然显示"您靠近商店",即使我要求位置。
这是因为它首先返回缓存的值。
好吧,我不是愚蠢,所以我修复了它:
(我将有效位置保存到UserLocation对象中(
因此,当用户关闭应用并返回时,它会检查位置是否太旧了。被称为
但仍然,在didupdatelecations函数中,它检查了位置是否太旧了,如果不是,则是新的,然后我确实从NET获取新数据
// Location Functions
func setupLocationManager(){
let authorizationStatus = CLLocationManager.authorizationStatus()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization()
locationManager?.startUpdatingLocation() // Log only significant location changes
locationManager?.pausesLocationUpdatesAutomatically = true // If user is not moving, don't update location
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters // Ten meter accuracy
locationManager?.distanceFilter = 20 // Update location only if 20m location change
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.last
// Check if location is not too old.. (aka cached)
let locationIsValid:Bool = Date().timeIntervalSince(currentLocation!.timestamp) < 11
if locationIsValid
{
currentLocationValue = currentLocation?.coordinate
// If first loc after opening / returning to app, then fetch data
if (userLocation.latitude == nil && userLocation.longitude == nil){
userLocation.location = currentLocation
userLocation.latitude = currentLocationValue?.latitude
userLocation.longitude = currentLocationValue?.longitude
mainFetchData()
}
userLocation.location = currentLocation
userLocation.latitude = currentLocationValue?.latitude
userLocation.longitude = currentLocationValue?.longitude
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// Error so remove global variable user location
userLocation.location = nil
userLocation.latitude = nil
userLocation.longitude = nil
}
// THIS GETS CALLED EVERYTIME applicationDidBecomeActive !
@objc func notification_validateCachedLocation(){
if userLocation.location != nil {
let lastCachedLocationIsInvalid:Bool = Date().timeIntervalSince(userLocation.location!.timestamp) > 10
if lastCachedLocationIsInvalid
{
userLocation.location = nil
userLocation.latitude = nil
userLocation.longitude = nil
locationManager?.requestLocation()
}
} else {
locationManager?.requestLocation()
}
}
但仍然有一个问题:
假设您只是在家...您打开了应用程序,它可以节省您的位置。然后您将其关闭。
好吧,所以在选址大约20分钟后,您返回并再次打开应用程序。
然后,位置manager加载位置,并且由于您从那以后还没有移动,因此不会更新。因此,它将超过10秒钟,它将只是一个缓存的位置,因此我的应用不会获取数据:C
在我看来,您应该停止使用PausesLocationUpdatesAutomply,然后手动暂停(停止定位(有时适合您。