iLucas97 iLucas97 - 10 months ago 106
iOS Question

CLLocation speed return -1.0

I have problem. My GPS (on iPad mini 2 in Wifi and on iPhone 6 in 3G/4G) the speed return -1.0. Have an idea?
This what i receive in console log:

Long: 12.5245, Lat: 41.9456, Speed:-1.0, kph: -3.6

Here the code in didUpdateLocations()

let userLocation: CLLocation = locations[0]
var speed: CLLocationSpeed = CLLocationSpeed()
speed = (locationManager.location?.speed)!

SpeedLabel.text = String(format: "%.0f km/h", speed * 3.6)
let long = String(Float(userLocation.coordinate.longitude))
let lat = String(Float(userLocation.coordinate.latitude))

print("Long: \(long), Lat: \(lat), Speed:\(speed), kph: \(speed * 3.6) ")


I had this problem too. A negative value means an invalid speed. This is most of the time occured when you're inside a building and your location is moving a lot due to the building.

A simple fix would be:

if speed < 0 { 
    speed = 0 

This checks if the speed is negative. If it is, it'll reset it to 0.