两个 CLLocation 点之间的距离值没有出现在标签文本上

Value of distance between 2 CLLocation points does not appear on label text

我正在尝试计算从我所在的起始位置(当我第一次启动应用程序时)到当前位置的距离,并将其显示在标签上 (meters.text),但上面什么也没有出现。 这是我的代码:

import UIKit
import CoreLocation

class CorrectViewController: UIViewController,CLLocationManagerDelegate {

@IBOutlet weak var meters: UILabel!
    var wr: Int = 0
    var distance = CLLocationDistance()
    let locationManager = CLLocationManager()


    override func viewDidLoad() {
    super.viewDidLoad()

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization() //starts when i use the app
    self.locationManager.distanceFilter = kCLHeadingFilterNone
    self.locationManager.startUpdatingLocation()
        }

        //locatioManager delegate method
        func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
            let currentLocation: CLLocation = newLocation
            let startLocation: CLLocation = oldLocation
            distance = startLocation.distanceFromLocation(currentLocation)
            let tripString = NSString(format: "%.2f", distance)
            meters.text = ("\(tripString)")
  }


func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    meters.text = ("error!")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

感谢任何帮助:)

位置更新委托方法似乎在 viewDidLoad 函数内部,因此定义了一个本地函数而不是实现委托方法。

将以下方法移出 viewDidLoad 范围:

locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) 

此外,您并未请求使用用户位置的权限。确保这样做并将必要的字符串添加到您的信息列表中。

另外:oldLocation 将始终是之前的位置(不是您的初始位置)。

好的,经过大量搜索 "trial and error" 我找到了解决方案 here。 应该使用 didUpdateLocations 方法,而不是使用 didUpdateToLocation 方法。此外,将 NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 键放入 .plist 文件中非常重要(值可能是将在位置中显示的附加消息警报)。 iOS 8.

中需要这些键