Search code examples
swiftfunctionmethodsdistancetracking

Calculate total distance swift iOS


So in my current project Im doing a method which calculates the saved emission when driving a moped compared to a average car. The function contains two parts, the method (the calculation) and the tracker function. The main problem is that the tracker function somehow does not seem to track at all.

My main question is, how do I get the tracker function to always track while the app is on?

This is the 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
}

And this is the method

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
}

Solution

  • Make sure you have the following in your info.plist. Then you should get prompted to allow access to the location services.

    <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>
    

    You should have some thing like this in viewDidLoad.

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