Search code examples
iosswiftcllocation

locationManager.location is always nil


I have essentially lifted this code from the internet:

//variables
//location manager
var locationManager:CLLocationManager!
var currentLocation:CLLocation?

//outlets
@IBOutlet weak var whatTextField: UITextField!
@IBOutlet weak var whereTextField: UITextField!
@IBOutlet weak var whenTextField: UITextField!

@IBAction func onCreateEventClick(_ sender: Any) {

    let event = CAEvent(eventId: "123777abc", eventName: whatTextField.text, location: currentLocation)
    event.save { (error) in
        //handle event error
        print(error)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
}

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

    if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
        CLLocationManager.authorizationStatus() ==  .authorizedAlways){
        determineCurrentLocation()
    }
}


func determineCurrentLocation() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()

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

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

    // Call stopUpdatingLocation() to stop listening for location updates,
    // other wise this function will be called every time when user location changes.
    // manager.stopUpdatingLocation()

    print("user latitude = \(currentLocation?.coordinate.latitude)")
    print("user longitude = \(currentLocation?.coordinate.longitude)")
}

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

And at first I was able to see the location (e.g., not nil.). Now however, it is nil every single time. I have tried changing my simulator's location, and I have confirmed that the app in my simulator is sharing location. I also have added a call to startUpdatingLocation() and added the delegate didUpdateLocations and noticed that didUpdateLocationsAny is not called. Any other ideas? Thanks!


Solution

  • Do you call locationManager's method startUpdatingLocation()? The best place to start updating location is locationManager's delegate method:

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch(CLLocationManager.authorizationStatus()) {
        case .authorizedAlways, .authorizedWhenInUse:
            locationManager.startUpdatingLocation()
        case .denied, .notDetermined, .restricted:
            locationManager.stopUpdatingLocation()
        }
    }