1

I am new to Swift. I had implemented Google maps sdk also I want to display the speed when the user starts moving or driving his/her car.

I am using CLLocationSpeed and storing it in a variable.

Right now I am getting the speed value when user clicks start button for navigation but its not changing as the user moves. I want to make it more dynamic.

I have attached the code and image for the label for the same:

 c

 var locationManager: CLLocationManager
 var speedlabel: UILabel = UILabel()
 var timerspeed: Timer?
 var speed: CLLocationSpeed = CLLocationSpeed()


@objc func runspeedcheck() {
        speedlabel.text = "\(speed)kph"
        
    }

func startnavigation {

 timerspeed = Timer(timeInterval: 1.0, target: self, selector: #selector(runspeedcheck), userInfo: nil, repeats: true)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        speed = locationManager.location!.speed
}

Is it right way to make it more dynamic, or is there any way to make changes in the speed label as the user moves?

halfer
  • 19,824
  • 17
  • 99
  • 186
Deven Nazare
  • 538
  • 5
  • 24

2 Answers2

1

There is no need to create a separate CLLocationSpeed variable to get the speed updates.

You can simply do it like so,

class VC: UIViewController, CLLocationManagerDelegate {
    @IBOutlet weak var speedlabel: UILabel!
    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let speed = manager.location?.speed {
            self.speedlabel.text = String(describing: speed)
        }
    }
}

Above is the sample code. Modify it as per your requirement.

PGDev
  • 23,751
  • 6
  • 34
  • 88
0
   func getUserSpeed() {
     var speed: CLLocationSpeed = CLLocationSpeed()
     guard let userSpeed = locationManager.location?.speed else { return }
     speed = userSpeed
     if speed < 0 { speed = 0 }
    speedLabel.text = String(format: "%.0f km/h", speed * 3.6)
   }
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Adrian Mole Jul 31 '20 at 14:20