当应用程序处于后台时,我可以将用户的当前位置发送到服务器吗?例如:在我的应用程序中,我想每 2 分钟存储一次用户的当前位置,然后将其当前位置发送到服务器。当应用程序处于后台时我可以执行此操作吗?我可以在后台模式下向服务器发送位置更新吗?如何发送?
最佳答案
您可以编辑距离或精度,请确保在功能中检查后台模式的位置。该代码在应用程序关闭时起作用。如果您只想要后台模式,您可以设置计时器并使用 UIBackgroundTask 发送发布请求,如下代码所示。
import UIKit
import Foundation
import CoreLocation
final class LocationManager: NSObject {
static let shared = LocationManager()
private var backgroundTask = UIBackgroundTaskIdentifier.invalid
private let manager = CLLocationManager()
func startMonitoring() {
manager.delegate = self
manager.pausesLocationUpdatesAutomatically = false
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
manager.distanceFilter = 1000.0
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
print("LocationManager didStartMonitoringFor")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("LocationManager \(error)")
}
func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
print("LocationManager \(error)")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
postLocation(location: locations.first)
}
}
extension LocationManager {
private func postLocation(location: CLLocation?) {
guard let location = location else { return }
if UIApplication.shared.applicationState == .background {
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "test_Location", expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskIdentifier.invalid
})
DispatchQueue.global(qos: .background).async {
self.postRequest(location: location) { [weak self] in
guard let self = self else { return }
UIApplication.shared.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskIdentifier.invalid
}
}
} else {
postRequest(location: location)
}
}
private func postRequest(location: CLLocation, completion: (() -> Void)? = nil) {
// TODO Send Post
}
}
关于ios - 如何在后台模式下获取当前位置并在后台模式下继续将该位置发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56850231/