Reputation: 1524
Here's a problem if I don't request "AuthorizedWhenInUse" status once my app first view controller is loaded I'll never get update after.
Let's say I have a map view controller. When I ask for status in the viewDidLoad
method it updates my location, i.e. func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
is called.
Now I added an intro view controller, once user finishes intro he/she is going to the old map controller. But now func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
isn't called anymore!
What I noticed is if I go to settings and toggle authorization status manually for my application and then get back to my app the didUpdateLocations
is called.
class MapViewController: UIViewController, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.distanceFilter = 100
locationManager.delegate = self
// >=iOS8
if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
locationManager.requestWhenInUseAuthorization()
} else {
locationManager.startUpdatingLocation()
}
}
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
manager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if let location = locations.first as? CLLocation {
println("User's location: \(location.description)")
} else {
println("User's location is unknown")
}
}
}
Upvotes: 2
Views: 1746
Reputation: 3523
I see several issues with what you posted, here are just two:
locationManager.startUpdatingLocation()
from viewDidLoad
this will only fire if the view is not already loaded into memory. Recommend moving this into viewWillAppear
so it fires every time.This code should be rewritten:
if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
locationManager.requestWhenInUseAuthorization()
} else {
locationManager.startUpdatingLocation()
}
You need to check the authorizationStatus
instead, if it is kCLAuthorizationStatusNotDetermined
then request permission using the if statement you have above. If you don't iOS 8 users will always drop into the requestWhenInUseAuthorization
section. You don't want that because the OS will only ask for permission once. It will not ask again unless you rest your phones Location Privacy under Settings.
Upvotes: 1