ios 检查是否启用了定位服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34861941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:35:43  来源:igfitidea点击:

Check if location services are enabled

iosswiftlocationios9swift3

提问by Brendan Chang

I've been doing some research about CoreLocation. Recently, I encountered a problem that has been covered elsewhere, but in Objective C, and for iOS 8.

我一直在做一些关于 CoreLocation 的研究。最近,我遇到了一个在其他地方已经讨论过的问题,但是在 Objective C 中,并且适用于 iOS 8。

I feel kinda silly asking this, but how can you check if location services are enabled using swift, on iOS 9?

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

On iOS 7 (and maybe 8?) you could use locationServicesEnabled(), but that doesn't appear to be working when compiling for iOS 9.

在 iOS 7(也许是 8?)上,您可以使用locationServicesEnabled(),但在为 iOS 9 编译时似乎不起作用。

So how would I accomplish this?

那么我将如何实现这一点?

Thanks!

谢谢!

回答by Rashwan L

Add the CLLocationManagerDelegateto your class inheritance and then you can make this check:

Swift 1.x - 2.x version:

添加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 version:

斯威夫特 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")
}

Swift 5.1 version

斯威夫特 5.1 版本

if CLLocationManager.locationServicesEnabled() {
    switch CLLocationManager.authorizationStatus() {
        case .notDetermined, .restricted, .denied:
            print("No access")
        case .authorizedAlways, .authorizedWhenInUse:
            print("Access")
        @unknown default:
        break
    }
    } else {
        print("Location services are not enabled")
}

回答by Marosdee Uma

In objective-c

在目标-c

you should track user already denied or not determined then ask for permission or sent user to Setting app.

您应该跟踪已被拒绝或未确定的用户,然后请求许可或将用户发送到设置应用程序。

-(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];
   }

}

Implement alertView Delegate then sent user to enable location service if already deny by user.

如果已经被用户拒绝,则实施 alertView Delegate 然后发送用户以启用位置服务。

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

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

Init Location Manager

初始化位置管理器

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

Please note kCLAuthorizationStatusAuthorizedAlways and kCLAuthorizationStatusAuthorizedWhenInUse is difference.

请注意 kCLAuthorizationStatusAuthorizedAlways 和 kCLAuthorizationStatusAuthorizedWhenInUse 是不同的。

回答by BennyTheNerd

SWIFT(As of July 24, 2018)

SWIFT (截至 2018 年 7 月 24 日)

if CLLocationManager.locationServicesEnabled() {

}

this will tell you if the user has already selected a setting for the app's location permission request

这将告诉您用户是否已经为应用的位置权限请求选择了设置

回答by Suat KARAKUSOGLU

It is just a 2 line function in Swift 4:

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

import CoreLocation

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

回答by Sri Hari YS

For swift3.0 and above , if frequent checks are made for the availability of location services, create a class like below,

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

and then use it like this in your VC

然后在你的 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)
        }
    }

回答by fs_tigre

Here is the format Applerecommends.

这是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
      }

Here is a complete example.

这是一个完整的例子。

This includes an AlertViewwith a button to take the user to the Settingsscreen if previously denied access.

这包括一个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
            }
        }
    }
}

回答by Shaheen Sharifian

When you call -startLocation, if location services were denied by the user, the location manager delegate will receive a call to - locationManager:didFailWithError: with the kCLErrorDeniederror code. This works both in all versions of iOS.

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

回答by Amul4608

In Swift 3.0

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

回答by Jess

To ask for permission for location services you use:

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

yourSharedLocationManager.requestWhenInUseAuthorization()

If the status is currently undetermined an alert will show prompting the user to allow access. If access is denied your app will be notified in the CLLocationManagerDelegate, likewise if permission is denied at any point you will be updated here.

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

There are two separate statuses you need to check to determine the current permissions.

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

  • If the user has the general location services enabled or not
  • 用户是否启用了一般位置服务

CLLocationManager.locationServicesEnabled()

CLLocationManager.locationServicesEnabled()

  • If the user has granted the correct permission for your app..
  • 如果用户为您的应用授予了正确的权限..

CLLocationManager.authorizationStatus() == .authorizedWhenInUse

CLLocationManager.authorizationStatus() == .authorizedWhenInUse

You could add an extension is a handy option:

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

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

}

}

Here it is being accessed when the user has first requested directions:

当用户第一次请求方向时,它会被访问:

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

Here is the delegate:

这是代表:

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

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