Search code examples
swiftcore-locationxcode10

Not getting users current location in swift 4


Location is not being printed to console. I have had this exact code working before but since updating to Xcode 10 it is not print the users current location into the console.

var locationManager: CLLocationManager!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    determineMyCurrentLocation()
}


func determineMyCurrentLocation() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation

    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")

}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
    print("Error \(error)")
}

Info.plist: enter image description here


Solution

  • The problem is your Info.plist. You need all three keys:

    enter image description here

    Fix that and the app will spring to life. I pasted your code into a project, set up the Info.plist as shown, and it worked fine.

    You can actually omit "Always" starting in iOS 11, but you must have both "When In Use" and "Always and When In Use", even if you are planning to ask only for "Always".

    The runtime was in fact telling you this all along in the Xcode console, but you apparently weren't looking at it. It says:

    The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data.