【发布时间】:2018-02-10 23:28:23
【问题描述】:
我正在制作一个应用程序,我必须知道该位置是否有效、未缓存且是最新的。
这是一个显示你身边的东西的应用程序(带有数据库和东西)
每 10 秒我从网上获取数据并在 tableView 中显示新数据。
假设我在一家商店附近,应用显示“您在商店附近”
我关闭应用程序,回家,当我打开应用程序时,即使我请求了位置,它仍然显示“您在商店附近”..
这是因为它先返回一个缓存的值..
好吧,我没那么笨,所以我修好了:
(我将有效位置保存到 userLocation 对象中)
所以当用户关闭应用程序并返回时,它会检查位置是否太旧。如果是,则 userLocation 对象被清除,locationManager?.requestLocation()被调用
但是,在 didUpdateLocations 函数中,它会检查位置是否太旧,如果不是,也就是新位置,那么我会从网上获取新数据
// 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 分钟后,您返回并再次打开应用程序..
然后 LocationManager 会加载位置,并且因为您从那以后没有移动,所以它不会得到更新。因此,它将超过 10 秒,它只是一个缓存位置,因此我的应用程序不会获取数据:C
【问题讨论】:
标签: swift locationmanager