Declare variable is your *.m class
@implementation your_class
{
CLLocationDistance _distance;
CLLocation *_lastLocation;
NSDate *_startDate;
}
In your init
or viewDidLoad
method set them to initial values
_distance = 0;
_lastLocation = nil;
_startDate = nil;
Change locationUpdate:
to
- (void)locationUpdate:(CLLocation *)location {
speedLabel.text = [NSString stringWithFormat:@"%.2f", [location speed]*2.236936284];
if (_startDate == nil) // first update!
{
_startDate = location.timestamp;
_distance = 0;
}
else
{
_distance += [location distanceFromLocation:_lastLocation];
_lastLocation = location;
NSTimeInterval travelTime = [location.timestamp timeIntervalSinceDate:_startDate];
if (travelTime > 0)
{
double avgSpeed = _distance / travelTime;
AVGspeedlabel.text = [NSString stringWithFormat: @"%.2f", avgSpeed];
NSLog(@"Average speed %.2f", avgSpeed);
}
}
}
to reset average speed
_startDate = nil;
_distance = 0;