iosswiftlocationcore-locationcllocationmanager

How to get current longitude and latitude using CLLocationManager-Swift


I want to get the current longitude and latitude of a location using Swift and display them via labels. I tried to do this but nothing displays on the labels.

import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate{

    @IBOutlet weak var longitude: UILabel!
    @IBOutlet weak var latitude: UILabel!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        if (CLLocationManager.locationServicesEnabled()) {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        } else {
            println("Location services are not enabled");
        }
    }

    // MARK: - CoreLocation Delegate Methods

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
         locationManager.stopUpdatingLocation()
         removeLoadingView()
         if (error) != nil {
             print(error)
          }
     }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate
        longitude.text = coord.longitude
        latitude.text = coord.latitude
        longitude.text = "\(coord.longitude)"
        latitude.text = "\(coord.latitude)"
    }
}

Solution

  • IMHO, you are over complicating your code when the solution you are looking is pretty simple.

    I have done it by using the following code:

    First create an instance of CLLocationManager and Request Authorization

    var locManager = CLLocationManager()
    locManager.requestWhenInUseAuthorization()
    

    then check if the user allowed authorization.

    var currentLocation: CLLocation!
    
    if 
       CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
       CLLocationManager.authorizationStatus() ==  .authorizedAlways
    {         
        currentLocation = locManager.location        
    }
    

    to use it just do this

    label1.text = "\(currentLocation.coordinate.longitude)"
    label2.text = "\(currentLocation.coordinate.latitude)"
    

    Your idea of setting them to the label.text is correct, however the only reason I can think of is that the user is not giving you permission and that is why your current Location data will be nil.

    However you would need to debug and tell us that. Also the CLLocationManagerDelegate is not necessary.

    Hopefully this helps. Ask away if you have doubts.