我正在尝试向用户显示两个位置之间的距离。他们点击开始按钮,前往目的地并按下停止按钮。然后,距离将显示在标签上。它是计算围场宽度所以需要从a点到b点的直线。
我可以运行代码,但只是崩溃。
这是我到目前为止的代码:
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"
}
}
有人能看出为什么这不起作用吗?
谢谢,乔希