【发布时间】:2017-06-11 16:19:05
【问题描述】:
我正在开发一个需要使用计时器每 10 分钟更新一次位置的屏幕。除此之外,它只需要在第一次加载和视图再次出现给用户时更新位置。一旦用户转到另一个视图,它应该停止监视。
我有一个应该执行此操作的代码,但问题是 didUpdateLocations 方法在任何时候都没有被调用。地图也没有显示当前位置(我使用模拟位置)。
我已正确设置权限,并且应用程序在设置为仅显示位置时运行良好。我需要这样做以减少电池消耗。
这是我的相关代码:
在viewDidLoad:
if #available(iOS 8.0, *) {
self.locationManager.requestAlwaysAuthorization()
}
self.locationManager.allowsBackgroundLocationUpdates = true
self.locationManager.distanceFilter = 1000
self.locationManager.activityType = CLActivityType.automotiveNavigation
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.pausesLocationUpdatesAutomatically = false
self.locationManager.startUpdatingLocation()
self.map.showsUserLocation = true
在viewWillAppear:
self.map.showsUserLocation = true
self.locationManager.startUpdatingLocation()
在viewWillDisappear:
self.map.showsUserLocation = false
self.locationManager.stopUpdatingLocation()
在didUpdateLocations:(最后一行)
self.locationManager.stopUpdatingLocation()
定时器功能:(这可以正常调用)
Timer.scheduledTimer(timeInterval: 600.0, target: self, selector: #selector(HomePageViewController.updateLocationFromTimer), userInfo: nil, repeats: true)
@objc func updateLocationFromTimer()
{
self.locationManager.startUpdatingLocation()
}
我还尝试使用以下代码捕获任何错误:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
但它没有被调用。
我很想知道为什么没有更新该位置以及为什么地图没有显示该位置。请帮忙。
【问题讨论】:
-
位置管理器的
delegate在哪里设置? -
我错误地删除了那行:(现在一切都好!非常感谢。
标签: ios swift swift3 cllocationmanager