在后台Swift中发送用户的位置

Bra*_*ayU 2 core-location ios firebase swift firebase-realtime-database

我正在构建一个应用程序,其中用户单击按钮,并且持续60分钟(或任何时间),我们通过将其位置上传到服务器来跟踪它们。目前,我们正在使用“更新位置”功能将用户位置实时发送到Firebase。

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

}
Run Code Online (Sandbox Code Playgroud)

该系统可以运行,但是它向服务器发送垃圾邮件,每秒将用户的位置发送到服务器一次。

这是太多数据,我们仅需要每10-30秒将用户位置发送到服务器一次。

每隔10到30秒我们该怎么发送一次用户位置信息?

Shm*_*idt 6

class ViewController: UIViewController, CLLocationManagerDelegate {
    private var locman = CLLocationManager()
    private var startTime: Date? //An instance variable, will be used as a previous location time.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    guard let loc = locations.last else { return }

    let time = loc.timestamp

    guard var startTime = startTime else {
        self.startTime = time // Saving time of first location, so we could use it to compare later with second location time.
        return //Returning from this function, as at this moment we don't have second location. 
    }

    let elapsed = time.timeIntervalSince(startTime) // Calculating time interval between first and second (previously saved) locations timestamps.

    if elapsed > 30 { //If time interval is more than 30 seconds
        print("Upload updated location to server")
        updateUser(location: loc) //user function which uploads user location or coordinate to server.

        startTime = time //Changing our timestamp of previous location to timestamp of location we already uploaded.

    }
}
Run Code Online (Sandbox Code Playgroud)