LoginSignup
1
2

More than 3 years have passed since last update.

[Swift] CoreLocationを使って現在地の経度と緯度を取得するサンプル

Posted at

概要

CoreLocation を使って現在地の経度と緯度を取得するサンプルです。

環境

Xcode 12
Swift 5

サンプルコード

ViewController.swift

import UIKit
import CoreLocation

class ViewController: UIViewController {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        // locationManagerのデリゲートを受け取る
        locationManager.delegate = self
        // アプリの使用中に位置情報サービスを使用する許可をリクエストする
        locationManager.requestWhenInUseAuthorization()
        // ユーザーの位置情報を1度リクエストする
        locationManager.requestLocation()
    }
}

//MARK: - CLLocationManagerDelegate

extension ViewController: CLLocationManagerDelegate {
    // 位置情報を取得・更新したときに呼ばれる
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // 最後に収集したlocationを取得
        if let location = locations.last {
            // 経度と緯度を取得
            let lat = location.coordinate.latitude
            let lon = location.coordinate.longitude
            print("lat: \(lat), lon: \(lon)")
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }

}

info.plist

Key: Privacy - Location When In Use Usage Description
Value: "このアプリは位置情報を使用します"

CoreLocation

デバイスの位置情報を取得するフレームワーク。
利用する際は import して使う。

requestLocation()

このメソッドを利用する場合、locationManager(_:didUpdateLocations:)locationManager(_:didFailWithError:) を実装しなければエラーとなる。

info.plist

KeyValue をそれぞれセットし、利用目的を明記しなければ位置情報を取得できないので注意。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2