检查是否启用了定位服务

检查是否启用了定位服务

本文介绍了检查是否启用了定位服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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

那么我将如何做到这一点?

So how would I accomplish this?

谢谢!

推荐答案

CLLocationManagerDelegate 添加到您的类继承中,然后您可以进行此检查:

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

导入 CoreLocation 框架

Import CoreLocation Framework

import CoreLocation

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

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

iOS 14.x

在 iOS 14 中,您将收到以下错误消息:authorizationStatus() 在 iOS 14.0 中被弃用

要解决此问题,请使用以下方法:

iOS 14.x

In iOS 14 you will get the following error message:authorizationStatus() was deprecated in iOS 14.0

To solve this, use the following:

private let locationManager = CLLocationManager()

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

这篇关于检查是否启用了定位服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:05