Reputation: 125
I want my app to show the user's location but it doesn't ask for WhenInUseAuthorization. I added the NSLocationWhenInUseUsageDescription key in the Info.plist. I tried in the iOS simulator with simulate location & on an actual device.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if CLLocationManager.authorizationStatus() == .NotDetermined {
self.locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
let userLocation = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude)
mapView.region = MKCoordinateRegionMakeWithDistance(userLocation, 100, 100)
} else {
let defaultLocation = CLLocationCoordinate2DMake(45.5017, -73.5673)
mapView.region = MKCoordinateRegionMakeWithDistance(defaultLocation, 100, 100)
}
}
}
Upvotes: 1
Views: 2006
Reputation: 125
This was my mistake, I added the NSLocationWhenInUseUsageDescription key in the test folder's Info.plist instead of the main project's plist.
Upvotes: 1
Reputation: 7451
Maybe you call requestWhenInUseAuthorization too early. Try to call in didChangeAuthorizationStatus
delegate.
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.NotDetermined {
locationManager.requestWhenInUseAuthorization()
}
}
Upvotes: 0
Reputation: 3484
Have you changed user location on simulator? If you didn't change it, you can't get the "user location".
Upvotes: 0