【Swift】現在の位置情報を取得する方法

iOSアプリでスマホの位置情報を取得する方法をご紹介します。

環境はSwift5, iOS13です。

シュミレータの場合、デフォルトの現在位置はカリフォルニア州のサンフランシスコになります。

デフォルトから変更したい場合は、Xcodeで世界の主要都市の位置情報を設定することができます。

Info.plistで規約を設定する

位置情報を取得するために必要なDescriptionは2つあります。

「Privacy – Location Always Usage Description」と「Privacy – When In Use Usage Description」です。

この2つの違いについては、Appleのドキュメントを見ると以下のように書いてあります。

Use this key if your iOS app accesses location information in the background, and you deploy to a target earlier than iOS 11. In that case, add both this key and NSLocationAlwaysAndWhenInUseUsageDescription to your app’s Info.plist file with the same message. Apps running on older versions of the OS use the message associated with NSLocationAlwaysUsageDescription, while apps running on later versions use the one associated with NSLocationAlwaysAndWhenInUseUsageDescription.

https://developer.apple.com/documentation/bundleresources/information_property_list/nslocationalwaysusagedescription

iOS10以前では「Always Usage Description」のメッセージが表示されて、iOS11以降だと「When In Use」のメッセージが表示されるようです。

「位置情報を常に取得します」よりも「アプリ使用中に」だとプライバシーが考慮されている感じがします。

iOSのバージョンによって異なるようなので両方とも記載しておきます。

Keyの名前は長いのですが、大文字のPを入力すると予測変換が出てきます。

打ち間違えの無いように予測変換を利用します。

ViewControllerの実装方法

`CLLocationManagerDelegate`プロトコルに批准します。

class MapVC: UIViewController, CLLocationManagerDelegate{
 :
}

位置情報の許可がユーザから得られたらdelegateを設定します。

    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
       if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }
     }

`CLLocationManagerDelegate`プロトコルに批准すると、位置情報がアップデートされるたびに以下のメソッドが呼ばれます。

この例では経度と緯度を表示するようにしています。

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
        print("locations = \(locValue.latitude) \(locValue.longitude)")
       }

参考

https://www.zerotoappstore.com/how-to-get-current-location-in-swift.html

ABOUTこの記事をかいた人

個人アプリ開発者。Python、Swift、Unityのことを発信します。月間2.5万PVブログ運営。 Twitter:@yamagablog