计算旅行时间CLLocation Swift

时间:2016-04-04 13:54:23

标签: ios swift cllocationmanager cllocation

我想在用户开始跟踪对象时使用swift 2.2查找移动物体的行程时间。我写了locationManager函数来跟踪移动物体的位置和行程距离但我需要找到旅行时间吗?

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

2 个答案:

答案 0 :(得分:0)

我的答案将是obj-c,因为我还没学过swift :)。但你会明白的。

在这类课程中,您可以创建2个日期:

NSDate *startDate;
NSDate *stopDate;

然后在你的startTrip方法中初始化startDate:

startDate = [NSDate date]; 

并在stopTrip中初始化stopDate并计算行程时间:

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

此外,如果您使用MKMaps,则在MKDirections类中有一个方法

-(void)calculateETAWithCompletionHandler:(MKETAHandler)completionHandler

可让您计算估计的行程时间

答案 1 :(得分:0)

您可以在设置startLocation时保存startDate,并使用NSDate timeIntervalSinceDate方法计算行程已用时间:

首先将startDate对象和计算属性添加到视图控制器:

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

然后在设置startLocation后设置startDate:

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

使用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) ?? ""
    }
}

现在你可以查看traveledTime:

print("travel elapsed time: \(traveledTime.positionalTime)")