Проверьте, включены ли службы определения местоположения
Я занимаюсь некоторыми исследованиями в области CoreLocation. Недавно я столкнулся с проблемой, которая была рассмотрена в другом месте, но в Objective C и для iOS 8.
Я чувствую себя глупо, спрашивая об этом, но как вы можете проверить, включены ли службы определения местоположения с помощью swift, на iOS 9?
В iOS 7 (и, возможно, 8?) вы можете использовать locationServicesEnabled()
, но это не работает при компиляции для iOS 9.
Итак, как бы я это сделал?
Спасибо!
Ответы
Ответ 1
Добавьте CLLocationManagerDelegate
к вашему наследованию класса, а затем выполните эту проверку:
Swift 1.x - 2.x версия:
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .NotDetermined, .Restricted, .Denied:
print("No access")
case .AuthorizedAlways, .AuthorizedWhenInUse:
print("Access")
}
} else {
print("Location services are not enabled")
}
версия Swift 3.0:
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined, .restricted, .denied:
print("No access")
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
}
} else {
print("Location services are not enabled")
}
Ответ 2
SWIFT 3 (по состоянию на 4 июля 2017 года)
if CLLocationManager.locationServicesEnabled() {
}
это скажет вам, если пользователь уже установил параметр для местоположения
Ответ 3
Когда вы вызываете -startLocation, если службы определения местоположения были отклонены пользователем, делегат менеджера местоположений получит вызов - locationManager:didFailWithError
: с кодом ошибки kCLErrorDenied
. Это работает как во всех версиях iOS.
Ответ 4
В objective-c
вы должны отследить пользователя, уже отказавшего или не определенного, затем попросите разрешения или отправите пользователя в приложение "Настройка".
-(void)askEnableLocationService
{
BOOL showAlertSetting = false;
BOOL showInitLocation = false;
if ([CLLocationManager locationServicesEnabled]) {
switch ([CLLocationManager authorizationStatus]) {
case kCLAuthorizationStatusDenied:
showAlertSetting = true;
NSLog(@"HH: kCLAuthorizationStatusDenied");
break;
case kCLAuthorizationStatusRestricted:
showAlertSetting = true;
NSLog(@"HH: kCLAuthorizationStatusRestricted");
break;
case kCLAuthorizationStatusAuthorizedAlways:
showInitLocation = true;
NSLog(@"HH: kCLAuthorizationStatusAuthorizedAlways");
break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
showInitLocation = true;
NSLog(@"HH: kCLAuthorizationStatusAuthorizedWhenInUse");
break;
case kCLAuthorizationStatusNotDetermined:
showInitLocation = true;
NSLog(@"HH: kCLAuthorizationStatusNotDetermined");
break;
default:
break;
}
} else {
showAlertSetting = true;
NSLog(@"HH: locationServicesDisabled");
}
if (showAlertSetting) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"Please enable location service for this app in ALLOW LOCATION ACCESS: Always, Go to Setting?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Open Setting", nil];
alertView.tag = 199;
[alertView show];
}
if (showInitLocation) {
[self initLocationManager];
}
}
Внедрить alertView. Затем делегат отправил пользователя для включения службы определения местоположения, если пользователь уже отклонил его.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
Начальный менеджер местоположений
-(void)initLocationManager{
self.locationManager = [[CLLocationManager alloc] init];
if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
}
Обратите внимание: kCLAuthorizationStatusAuthorizedAlways и kCLAuthorizationStatusAuthorizedWhenInUse - разница.
Ответ 5
Для swift3.0 и выше,
если для проверки доступности служб местоположения проводятся частые проверки, создайте класс, как показано ниже,
import CoreLocation
open class Reachability {
class func isLocationServiceEnabled() -> Bool {
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
case .notDetermined, .restricted, .denied:
return false
case .authorizedAlways, .authorizedWhenInUse:
return true
default:
print("Something wrong with Location services")
return false
}
} else {
print("Location services are not enabled")
return false
}
}
}
а затем используйте его в своем VC
if Reachability.isLocationServiceEnabled() == true {
// Do what you want to do.
} else {
//You could show an alert like this.
let alertController = UIAlertController(title: "Location
Services Disabled", message: "Please enable location services
for this app.", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default,
handler: nil)
alertController.addAction(OKAction)
OperationQueue.main.addOperation {
self.present(alertController, animated: true,
completion:nil)
}
}
Ответ 6
Это всего лишь 2-строчная функция в Swift 4:
import CoreLocation
static func isLocationPermissionGranted() -> Bool
{
guard CLLocationManager.locationServicesEnabled() else { return false }
return [.authorizedAlways, .authorizedWhenInUse].contains(CLLocationManager.authorizationStatus())
}
Ответ 7
В Swift 3.0
if (CLLocationManager.locationServicesEnabled())
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if ((UIDevice.current.systemVersion as NSString).floatValue >= 8)
{
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
}
else
{
#if debug
println("Location services are not enabled");
#endif
}