title: Trouble getting one-time user location in Swift
body: <p>I am trying to get the user's location at the time of a button press, however I am having trouble setting up the location code. I've been looking between various answers on Stackoverflow but I can't get anything to work for me.</p>
  
  <pre><code>class MyViewController: UIViewController, CLLocationManagerDelegate {
  
  var locationManager = CLLocationManager()
  
  override func viewDidLoad() {
      super.viewDidLoad()
  
      locationManager.delegate = self
      locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
      locationManager.requestWhenInUseAuthorization()
      locationManager.startUpdatingLocation()
  
  }
  
  func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
      if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
          let latitude = self.locationManager.location?.coordinate.latitude
          let longitude = self.locationManager.location?.coordinate.longitude
          print("coordinates:")
          print(latitude)
          print(longitude)
      }
  }
  
  func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
      let locationValue : CLLocationCoordinate2D = manager.location!.coordinate
      print("locations = \(locationValue.latitude) \(locationValue.longitude)")
  }
  </code></pre>
  
  <p>However I just get nils from the prints in <code>didChangeAuthorizationStatus</code> and nothing ever prints from <code>didUpdateLocations</code>. Im also really confused about where to put <code>startUpdatingLocation()</code>. Some answers place it directly in <code>viewDidLoad</code> as I have here, others place it in <code>didChangeAuthorizationStatus</code>, and I saw another place it inside an <code>if CLLocationManager.locationServicesEnabled()</code> in didLoad. What is the correct way to do this? And also what have I done wrong that I'm not getting any values printing? I'm running on the emulator, have location turned on and allowed permissions in the pop-up, and have the emulator set to a lat/long custom location, and I have added the values in pList.</p>
  
  <p>edit: <a href="https://www.hackingwithswift.com/example-code/location/how-to-request-a-users-location-only-once-using-requestlocation" rel="nofollow">even tried copy/pasting the code from this to get user's location only once</a> but it returns <code>(kCLErrorDomain error 0.)</code>. I added a 'requestWhenInUseAuthorization()` to their code but it still fails.</p>