我希望在每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()
}
}发布于 2018-08-17 14:16:49
我也有类似的要求,但时间间隔是5分钟。
可能是你的应用程序处于空闲状态的时间更长(15分钟),即操作系统没有更新你的位置。
尝试保持较短的时间间隔,并尝试它将工作。
发布于 2018-08-17 17:39:46
您是否处理来自AppDelegate的应用程序状态的位置更新?如果没有,您可以在AppDelegate中使用以下方法更新您的代码。
var locationManager = CLLocationManager()
func doBackgroundTask() {
DispatchQueue.global(qos: .background).async {
self.beginBackgroundUpdateTask()
self.StartupdateLocation()
RunLoop.current.run()
}
}
func beginBackgroundUpdateTask() {
backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
self.endBackgroundUpdateTask()
})
}
func endBackgroundUpdateTask() {
UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
self.backgroundUpdateTask = UIBackgroundTaskInvalid
}
func StartupdateLocation() {
locationManager.startUpdatingLocation()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestAlwaysAuthorization()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
}当应用程序进入后台状态时,调用该方法。
func applicationWillResignActive(_ application: UIApplication) {
self.doBackgroundTask()
}此方法将帮助您在app后台获取位置更新。如果您遇到任何其他困难,可以查看此链接。Update location in Background
https://stackoverflow.com/questions/51888404
复制相似问题