Reputation: 229
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
Reputation: 2650
TLDR;
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
Reputation: 2193
Make sure you:
import Corelocation
+ import MapKit
in your class.MKMapViewDelegate
and CLLocationManagerDelegate
let locationManager = CLLocationManager()
in your class variablesin your viewDidLoad try:
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager. requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
Add the following delegate method to print your location:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations.last!.coordinate)
}
Upvotes: 1