在iOS swift 3中,当应用程序处于后台模式时,如何获得每10秒的经度和经度

时间:2017-11-07 11:57:46

标签: swift3 core-location

我开发了一个用于总线跟踪的应用程序,因为我想将驱动程序的纬度和经度发送到后端服务器,以便我更新当前位置。 但是当应用程序处于后台模式时,那么如何获得经纬度和经度????

1 个答案:

答案 0 :(得分:-1)

您需要使用CoreLocation框架和NSTimer

1:在项目中添加CoreLocation框架。 2:在“BackgroundModes”中允许"Location Update" enter image description here

2:在您要访问位置的YOURViewController或AppDelegate中添加:

import CoreLocation

class YourViewController: UIViewController, CLLocationManagerDelegate {

    // Location Manager 
    let locManager = CLLocationManager()

    override func viewDidLoad() {
      locManager.delegate = self
      // 300 = 300 seconds. Change time according to you. This is repeating funciton.
      let _ = Timer.scheduledTimer(timeInterval: TimeInterval(300), target: self, selector: #selector(self.getLocation), userInfo: nil, repeats: true)
    }

    func startUpdatingBugs()  {
        locManager.delegate         = self
        locManager.desiredAccuracy  = kCLLocationAccuracyBest;
        locManager.distanceFilter   = 10; // meters
        locManager.startUpdatingLocation()
    }

现在添加代理以获取位置并上传到服务器或其他任何内容。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        var geoLocationLongitude = location?.coordinate.longitude ?? "na",
        var geoLocationLattitude = location?.coordinate.latitude ?? "na",
}