1. ホーム
  2. ios

[解決済み] 位置情報サービスが有効かどうか確認する

2022-12-05 22:38:17

質問

CoreLocationについて調べています。最近、他の場所で取り上げられている問題に遭遇しましたが、Objective C で、iOS 8 のためのものでした。

これを聞くのはちょっとばかばかしいのですが、iOS 9 で swift を使って位置サービスが有効になっているかどうかを確認する方法はありますか?

iOS 7 (そしてたぶん 8?) では locationServicesEnabled() を使用することができましたが、iOS 9 用にコンパイルする際には機能しないようです。

では、どのようにこれを達成すればよいのでしょうか?

ありがとうございます。

どのように解決するのですか?

を追加します。 CLLocationManagerDelegate をクラス継承に追加すると、このようなチェックができるようになります。



CoreLocationフレームワークのインポート

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 で非推奨になりました。



これを解決するために、次のようにします。
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")
}