我希望该位置每3分钟更新一次。后台任务在第一次3分钟后工作,但在此之后不会重新启动。我需要反复而不是一次。
override func viewDidLoad()
{
super.viewDidLoad()
timer.invalidate()
timer = Timer.scheduledTimer(timeInterval: 179, target: self, selector: #selector(someBackgroundTask), userInfo: nil, repeats: true);
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
if CLLocationManager.locationServicesEnabled()
{
if status == CLAuthorizationStatus.notDetermined
{
locationManager.requestAlwaysAuthorization()
}
}else {
print("locationServices disenabled")
}
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
mapView.delegate = self
registerBackgroundTask()
}
func someBackgroundTask(timer:Timer) {
DispatchQueue.global(qos: .background).async {
self.locationManager.startUpdatingLocation()
timer.invalidate()
timer.fire()
self.registerBackgroundTask()
}
}
func registerBackgroundTask() {
backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
self?.someBackgroundTask(timer: (self?.timer)!)
self?.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
print("Background task ended.")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
答案 0 :(得分:2)
致电timer.invalidate
后,您必须再次使用Timer.scheduledTimer(...)
设置计时器。
检查参考https://developer.apple.com/reference/foundation/timer/1415405-invalidate
停止计时器
func invalidate()
阻止接收器发射 再次请求将其从运行循环中删除。
答案 1 :(得分:2)
您需要启用CLLocationManager的allowBackgroundLocationUpdates。
在Swift 2中,您还需要:
self.locationManager.allowsBackgroundLocationUpdates = true