2

I want to find travel time of moving object using swift 2.2 when user start tracking the object. I wrote locationManager function to track the moving object location and travel distance but I need to find travel time?

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    userLocations.append(locations[0] as CLLocation)

    if startLocation == nil {
        startLocation = locations.first! as CLLocation
    } else {
        let distance = startLocation.distanceFromLocation(locations.last! as CLLocation) / 1000
        let lastDistance = lastLocation.distanceFromLocation(locations.last! as CLLocation) / 1000;

        vartraveledDistance += lastDistance
        print( "\(startLocation)")
        print( "\(locations.last!)")
        print("FULL DISTANCE: \(traveledDistance)")

        print("STRAIGHT DISTANCE: \(distance)")
    }
    lastLocation = locations.last! as CLLocation
}


@IBAction func StartTrip(sender: AnyObject) {
    print("Start Trip")
    locationManager.startUpdatingLocation()
}

@IBAction func StopTrip(sender: AnyObject) {
    print("End Trip")
    locationManager.stopUpdatingLocation()
    traveledDistance.text = String(format:"%f km", self.vartraveledDistance)
}
dan
  • 9,695
  • 1
  • 42
  • 40
NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51

2 Answers2

1

You can save the startDate when you set the startLocation and use NSDate timeIntervalSinceDate method to calculate the travel elapsed time:

First add a startDate object and a computed property to your view controller:

var startDate: NSDate!
var traveledTime: Double { return NSDate().timeIntervalSinceDate(startDate) }

Then set the startDate after setting your startLocation:

if startLocation == nil {
    startLocation = locations.first
    startDate = NSDate()
    // code ...
}

Create an extension to format your time using NSDateComponentsFormatter:

extension NSTimeInterval {
    struct DateComponents {
        static let formatterPositional: NSDateComponentsFormatter = {
            let dateComponentsFormatter = NSDateComponentsFormatter()
            dateComponentsFormatter.unitsStyle = .Positional
            dateComponentsFormatter.allowedUnits = [.Hour,.Minute,.Second]
            dateComponentsFormatter.zeroFormattingBehavior = .DropLeading
            return dateComponentsFormatter
        }()
    }
    var positionalTime: String {
        return DateComponents.formatterPositional.stringFromTimeInterval(self) ?? ""
    }
}

Now you can just check the traveledTime:

print("travel elapsed time: \(traveledTime.positionalTime)")
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0

My answer will be in obj-c since I haven't learnt swift yet :). But you'll get the idea.

In this class of yours you can create 2 dates:

NSDate *startDate;
NSDate *stopDate;

And then in your startTrip method initialize the startDate:

startDate = [NSDate date]; 

and in stopTrip initialize the stopDate and calculate the travel time:

stopDate = [NSDate date];
NSTimeInterval interval = [startDate timeIntervalSinceDate:stopDate];
NSLog (@"Travel time = %.0f seconds", interval);

Also if you are using MKMaps, in MKDirections class there is a method

-(void)calculateETAWithCompletionHandler:(MKETAHandler)completionHandler

which lets you calculate the estimated time to travel

macL0vin
  • 183
  • 2
  • 11