检查是否启用了位置服务

时间:2016-01-18 18:50:15

标签: ios swift location ios9 swift3

我一直在做一些关于CoreLocation的研究。最近,我遇到了其他地方已经涉及的问题,但是在Objective C和iOS 8中。

我觉得有点傻傻问这个,但是如何在iOS 9上检查是否使用swift启用了位置服务?

在iOS 7(可能是8?)上你可以使用locationServicesEnabled(),但在编译iOS 9时这似乎不起作用。

那我该如何实现呢?

谢谢!

10 个答案:

答案 0 :(得分:186)

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 4.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")
}

答案 1 :(得分:9)

在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 Delegate,然后发送用户启用位置服务(如果已经被用户拒绝)。

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

   if (alertView.tag == 199) {
       if (buttonIndex == 1) {
           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
       }
       return;
   }
}

初始位置管理员

-(void)initLocationManager{
   self.locationManager = [[CLLocationManager alloc] init];
   if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
       [self.locationManager requestAlwaysAuthorization];
   }
}

请注意kCLAuthorizationStatusAuthorizedAlways和kCLAuthorizationStatusAuthorizedWhenInUse是不同的。

答案 2 :(得分:9)

SWIFT (截至2018年7月24日)

if CLLocationManager.locationServicesEnabled() {

}

这将告诉您用户是否已选择应用的位置许可请求的设置

答案 3 :(得分:5)

这只是Swift 4中的2行函数:

import CoreLocation

static func isLocationPermissionGranted() -> Bool
{
    guard CLLocationManager.locationServicesEnabled() else { return false }
    return [.authorizedAlways, .authorizedWhenInUse].contains(CLLocationManager.authorizationStatus())
}

答案 4 :(得分:4)

对于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)
        }
    }

答案 5 :(得分:4)

Apple建议使用以下格式。

  switch CLLocationManager.authorizationStatus() {
      case .notDetermined:
         // Request when-in-use authorization initially
         break

      case .restricted, .denied:
         // Disable location features
         break

      case .authorizedWhenInUse, .authorizedAlways:
         // Enable location features
         break
      }
   }

这是一个完整的例子。

这包括一个AlertView和一个按钮,如果以前拒绝访问,则将用户带到Settings屏幕。

import CoreLocation
let locationManager = CLLocationManager()

class SettingsTableViewController:CLLocationManagerDelegate{

    func checkUsersLocationServicesAuthorization(){
        /// Check if user has authorized Total Plus to use Location Services
        if CLLocationManager.locationServicesEnabled() {
            switch CLLocationManager.authorizationStatus() {

            case .notDetermined:
                // Request when-in-use authorization initially
                // This is the first and the ONLY time you will be able to ask the user for permission
                self.locationManager.delegate = self
                locationManager.requestWhenInUseAuthorization()
                break

            case .restricted, .denied:
                // Disable location features
                switchAutoTaxDetection.isOn = false
                let alert = UIAlertController(title: "Allow Location Access", message: “MyApp needs access to your location. Turn on Location Services in your device settings.", preferredStyle: UIAlertController.Style.alert)

                // Button to Open Settings
                alert.addAction(UIAlertAction(title: "Settings", style: UIAlertAction.Style.default, handler: { action in
                    guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                        return
                    }
                    if UIApplication.shared.canOpenURL(settingsUrl) {
                        UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                            print("Settings opened: \(success)") 
                        })
                    }
                }))
                alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil))
                self.present(alert, animated: true, completion: nil)

                break

            case .authorizedWhenInUse, .authorizedAlways:
                // Enable features that require location services here.
                print("Full Access")
                break
            }
        }
    }
}

答案 6 :(得分:3)

当您调用-startLocation时,如果用户拒绝了位置服务,则位置管理员委托将收到对locationManager:didFailWithError的调用:kCLErrorDenied错误代码。这适用于所有版本的iOS。

答案 7 :(得分:1)

在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
            }

答案 8 :(得分:1)

要求获得您使用的位置服务的许可:

yourSharedLocationManager.requestWhenInUseAuthorization()

如果状态当前未确定,则会显示警告提示用户允许访问。如果访问被拒绝,您的应用程序将在CLLocationManagerDelegate中得到通知,同样,如果在任何时候拒绝权限,您将在此处更新。

您需要检查两种不同的状态以确定当前的权限。

  • 如果用户启用了常规位置服务

CLLocationManager.locationServicesEnabled()

  • 如果用户已为您的应用授予了正确的权限..

CLLocationManager.authorizationStatus() == .authorizedWhenInUse

您可以添加扩展程序是一个方便的选项:

extension CLLocationManager {
static func authorizedToRequestLocation() -> Bool {
    return CLLocationManager.locationServicesEnabled() &&
        (CLLocationManager.authorizationStatus() == .authorizedAlways || CLLocationManager.authorizationStatus() == .authorizedWhenInUse)
}

}

当用户首次请求指示时,正在访问它:

 private func requestUserLocation() {
    //when status is not determined this method runs to request location access
    locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.authorizedToRequestLocation() {

        //have accuracy set to best for navigation - accuracy is not guaranteed it 'does it's best'
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation

        //find out current location, using this one time request location will start the location services and then stop once have the location within the desired accuracy -
        locationManager.requestLocation()
    } else {
        //show alert for no location permission
        showAlertNoLocation(locationError: .invalidPermissions)
    }
}

这是代表:

 func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

    if !CLLocationManager.authorizedToRequestLocation() {
        showAlertNoLocation(locationError: .invalidPermissions)
    }
}

答案 9 :(得分:1)

Swift 5.2

首先,将 User 类设置为 CLLocationManager 委托:

START TRANSACTION;
ALTER TABLE persons ADD phone varchar(20) NOT 
NULL AFTER City, check(phone like '001%');
INSERT INTO persons(LastName, FirstName, Address, 
City, phone) VALUES
('White', 'Tom', 'Brown St., No. 8', 
'LA','00189654789');
commit;

然后在视图中:

class User: NSObject, ObservableObject {

   let manager = CLLocationManager()

   override init() {
      super.init()
      manager.delegate = self
      manager.requestWhenInUseAuthorization()
      manager.requestLocation()
      manager.startUpdatingLocation()
   }
}

extension User: CLLocationManagerDelegate {

   func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
      print("Location services authorization request")
   }

   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
      print("Location updated")
   }

   func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
      print("Failed to find user's location: \(error.localizedDescription)")
   }
 }