gareth power
gareth power

Reputation: 229

I can't get Swift to give me a user's location

I am trying to get the user's location in Swift. Using the code below. But when I call

let currentloc = self.locationManager.location?.coordinate , it returns a nil value. The code below is above the let currentloc line in the script.

     self.locationManager.delegate = self
    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()

Upvotes: 0

Views: 209

Answers (2)

H4Hugo
H4Hugo

Reputation: 2650

TLDR;

  • Product -> Scheme -> Edit Scheme -> Options -> Allow Location Simulation must be checked and try providing a default location, don't leave it set to "none"

When you test on simulator, you have to provide a default location, please check my answer here : https://stackoverflow.com/a/32887820/4887400

Upvotes: 0

Hapeki
Hapeki

Reputation: 2193

Make sure you:

  1. import Corelocation + import MapKit in your class.
  2. conform to the MKMapViewDelegate and CLLocationManagerDelegate
  3. instantiate the locationmanager: let locationManager = CLLocationManager() in your class variables
  4. in your viewDidLoad try:

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager. requestAlwaysAuthorization()
    self.locationManager.startUpdatingLocation()
    self.mapView.showsUserLocation = true
    
  5. Add the following delegate method to print your location:

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print(locations.last!.coordinate)
    }
    

Upvotes: 1

Related Questions