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

298 Views Asked by At

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:)

2

There are 2 best solutions below

0
George_th On BEST ANSWER

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.

1
Felix Lamouroux On

It appears that the location update delegate method is inside the viewDidLoad function and hence defines a local function rather than implementing the delegate method.

Move the following method out of the viewDidLoad scope:

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

In addition you are not requesting permission to use the users location. Make sure to do that and add the necessary string to your info plist.

Also: oldLocation will always be the previous location (not your initial one).