计算总距离 swift iOS

Calculate total distance swift iOS

所以在我目前的 project 中,我正在使用一种方法来计算与普通汽车相比驾驶轻便摩托车时节省的排放量。该函数包含两部分,method(计算)和 tracker function。主要问题是跟踪器功能不知何故 似乎根本无法跟踪

我的主要问题是,如何让跟踪器功能在应用程序打开时始终跟踪?

这是跟踪器功能

var startLocation:CLLocation!
var lastLocation: CLLocation!
var traveledDistance:Double = 0

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

    if startLocation == nil {
        startLocation = locations.first
    } else {
        if let lastLocation = locations.last {
            let distance = startLocation.distanceFromLocation(lastLocation)
            let lastDistance = lastLocation.distanceFromLocation(lastLocation)
            traveledDistance += lastDistance
            print( "\(startLocation)")
            print( "\(lastLocation)")
            print("FULL DISTANCE: \(traveledDistance)")
            print("STRAIGHT DISTANCE: \(distance)")
            var travelDistance = setData("distance")
        }
    }
    lastLocation = locations.last
}

这就是方法

func calculateEmission(numbers: Int...) -> Double{
    let recordedDistance = getData("distance")

    let dis = recordedDistance
    let emissionAve = 0.16

    let calculatedEmission : Double = Double(dis) * Double(emissionAve)

    print(calculatedEmission, "kg Co2")
    return calculatedEmission
}

确保您的 info.plist 中包含以下内容。然后系统会提示您允许访问定位服务。

<key>NSLocationAlwaysUsageDescription</key>
<string>Needs access to access GPS</string>
<key>NSLocationUsageDescription</key>
<string>Needs access to access GPS</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Needs access to access GPS</string>

你应该在 viewDidLoad 中有这样的东西。

override func viewDidLoad() {
    self.locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }
    }