iosswiftcllocationmanagercllocationcllocationdistance

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


I am trying to calculate the distance from the starting position I am (when i first start the app) to the current position and present it on a label (meters.text) but nothing appears on it.. Here is my code:

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.
}

Any help is appreciated:)


Solution

  • Alright, after a lot of searching and "trial and error" I found the solution here. Instead of using the method didUpdateToLocation the method didUpdateLocations should be used. Moreover, it is really important to put NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys in the .plist file (value may be an additional message that will be presented in location alert). These keys are required in iOS 8.