2个CLLocation点之间的距离值不显示在标签文本上



我正试图计算从我所在的起始位置(第一次启动应用程序时)到当前位置的距离,并将其显示在标签(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) 

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

此外:oldLocation将始终是以前的位置(而不是您最初的位置)。

好吧,经过大量搜索和"反复试验",我在这里找到了解决方案。不应使用方法didUpdateToLocation,而应使用方法didUpdateLocations。此外,在.plist文件中放入NSLocationAlwaysUsageDescriptionNSLocationWhenUseUsageDescription键非常重要(值可能是将在位置警报中显示的附加消息)。这些密钥在iOS 8中是必需的。

最新更新