I am trying to display the distance between two locations to the user. They hit the start button, go to their destination and hit the stop button. The distance will then be displayed to a label. It is to calculate paddock widths so a straight line from point a to point b is required.
I can run the code but just get a crash.
Here is the code I have so far:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet var label: UILabel!
var locationManager = CLLocationManager()
var startLocation: CLLocation!
var endLocation: CLLocation!
var distanceTravelled = Double()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func startButton(_ sender: Any) {
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation()
} else {
// Get user to allow location under device settings.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if startLocation == nil {
startLocation = locations[0] as CLLocation
} else {
// Reset the locations.
}
}
}
@IBAction func stopButton(_ sender: Any) {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if endLocation == nil {
endLocation = locations[0] as CLLocation
} else {
// Reset the locations.
}
self.locationManager.stopUpdatingLocation()
}
distanceTravelled = startLocation.distance(from: endLocation)
label.text = "\(distanceTravelled) m"
}
}
Can anyone see why this isn't working?
Thanks, Josh