【发布时间】:2019-01-24 02:01:08
【问题描述】:
我想每 15 分钟将用户当前的Location 发送到服务器。当应用程序处于前台时,timer 正在运行,但当应用程序处于后台时,计时器未运行。我搜索了很多,但没有找到任何解决方案。你能告诉我我是做什么的吗?我正在使用以下代码进行后台位置同步,但它不起作用。
var locationManager = CLLocationManager()
var currentLocation: CLLocation?
var timer : Timer?
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
func getCurrentLocation()
{
// Do any additional setup after loading the view, typically from a nib.
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
//
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
let timer = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: true) { (timer) in
self.locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
print("locations = \(locations)")
if let location = locations.last
{
print("location\(String(describing: location.coordinate))")
currentLocation = location
locationManager.stopUpdatingLocation()
}
}
【问题讨论】:
-
确保: 1- 选中项目功能中的“位置更新”选项。 2-您的应用程序被允许检测以检测位置(来自iOS的许可)。
-
另请查看
significantLocationChangeMonitoringAvailable。看看这是否有更好的帮助,因为您的位置管理器呼叫会耗尽电池电量。 -
@adev 他已经做了...请检查代码!
-
@AhmadF,谢谢,不知怎的,我错过了。
-
每60秒启动一次计时器,它只工作3分钟,然后停止工作
标签: ios swift timer background location