Search code examples
iosxcodeswiftmapkitcllocation

CLLocationDistance not working - swift


I'm having problems with this code, I can't calculate the distance between two locations. I've already searched all over the internet but I could not solve it. Here is my didUpdateLocations function:

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

    var userLocation:CLLocation = locations[0] as CLLocation
    var startLocation = userLocation
    var endLocation = userLocation
    if x == 0 {
        var startLocation = userLocation
        star.text = "\(startLocation)"
    }
    if x > 0 {
        var endLocation = userLocation
        end.text = "\(endLocation)"
        let distance: CLLocationDistance = startLocation.distanceFromLocation(endLocation)
        println(distance)
    }
    x = x + 1
}

Solution

  • You just need to declare you var startLocation as an optional but not inside your function.

    var startLocation :CLLocation! 
    

    then inside your didUpdate function you just test if the startLocation var is nil:

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if startLocation == nil {
            startLocation = locations.first as? CLLocation
        }
        let distance = startLocation.distanceFromLocation(locations.last as! CLLocation)
        println( "\(startLocation)")
        println( "\(locations.last as! CLLocation)")
        println("DISTANCE: \(distance)")
    }