我希望位置每3分钟更新一次。后台任务在第一次3分钟后运行,但之后不会重新启动。我需要它重复发生,而不是一次。后台任务不能在Swift中重新启动
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
}
你不能在后台的时间表运行的任务。您应该启用后台位置更新以在用户移动时接收更新,或者如果您需要较低的准确性和较低的电池影响,则需要使用重要的位置更新 – Paulw11