I have noticed the following with a plain, completely new project in Xcode.
If, in the ViewController.swift file I import CoreLocation, and then in the viewDidLoad method I add...
print(CLLocationManager.locationServicesEnabled())
..., when the app runs in simulator Xcode prints out true. I would have thought that location services would be disabled by default, but as you can see for yourself, the opposite is true. If I wanted I could add some more code to gather location information about the user, and all this without ever having to ask for permission.
Can anybody explain why this is?
Basic Swift Code for iOS Apps You should check the return value of locationServiceEnabled() method before starting location updates to determine whether the user has location services enabled for the current device.
Go to Settings > Privacy > Location Services. Make sure that Location Services is on.
Users can enable or disable location services by toggling the Location Services switch in Settings > Privacy. When users disable the switch, the system calls your delegate's locationManager(_:didChangeAuthorization:) method with a denied authorization status ( CLAuthorizationStatus. denied ).
As far as I know, CLLocationManager.locationServicesEnabled() will return whether location Services are enabled on the device, not just for that one app. So even if location Services are disabled for that app, if they are enabled for the device, I think that will still return true, as per the documentation: https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/occ/clm/CLLocationManager/locationServicesEnabled
In my app, I set it up like this:
//check if location services are enabled at all
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
//check if services disallowed for this app particularly
case .Restricted, .Denied:
print("No access")
var accessAlert = UIAlertController(title: "Location Services Disabled", message: "You need to enable location services in settings.", preferredStyle: UIAlertControllerStyle.Alert)
accessAlert.addAction(UIAlertAction(title: "Okay!", style: .Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)
}))
presentViewController(accessAlert, animated: true, completion: nil)
//check if services are allowed for this app
case .AuthorizedAlways, .AuthorizedWhenInUse:
print("Access! We're good to go!")
//check if we need to ask for access
case .NotDetermined:
print("asking for access...")
manager.requestAlwaysAuthorization()
}
//location services are disabled on the device entirely!
} else {
print("Location services are not enabled")
}
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With