LoginSignup
4
3

More than 3 years have passed since last update.

iOS14で位置情報を取得する

Last updated at Posted at 2021-05-17

前書き

iOS14では、CoreLocationの仕組みが一部変更された。それにより、authorizationStatus()がDeprecatedになった。
今回は、iOS14環境で位置情報を取得する方法を記載します。

プログラム

ViewController.swift
import UIKit
import CoreLocation

class ViewController: UIViewController {
    var locationManager: CLLocationManager?

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager!.delegate = self
        locationManager!.requestWhenInUseAuthorization() // ユーザーの使用許可を確認

        // デバイスの位置情報が有効の場合
        if CLLocationManager.locationServicesEnabled() {
            locationManager!.desiredAccuracy = kCLLocationAccuracyBest // 測位精度(最高に設定)
            locationManager!.distanceFilter = 10 // 位置情報取得間隔
            locationManager!.activityType = .fitness // ユーザーアクティビティ(フィットネス)の設定
            locationManager!.startUpdatingLocation() // 位置情報の取得開始
        }
    }
}

// MARK:-- GPS
extension ViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let newLocation = locations.last else { return }
        let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(newLocation.coordinate.latitude, newLocation.coordinate.longitude)
        print("緯度: ", location.latitude, "経度: ", location.longitude)
    }
}

測位精度

  • kCLLocationAccuracyBestForNavigation
    • ナビゲーションアプリのための高い精度と追加のセンサーも使用する
  • kCLLocationAccuracyBest
    • 最高レベルの精度
  • kCLLocationAccuracyNearestTenMeters
    • 10メートル以内の精度
  • kCLLocationAccuracyHundredMeters
    • 100メートル以内の精度
  • kCLLocationAccuracyKilometer
    • キロメートルでの精度
  • kCLLocationAccuracyThreeKilometers
    • 3キロメートルでの精度

引用元:[iPhone] GPSなど位置情報をCoreLocationを使って取得

frameworkの設定

「BuildPhases」 → 「Link Binary With Libraies」 → 「+」 → 「CoreLocation.framework」の手順でCoreLocation.frameworkを追加する。
スクリーンショット 2021-05-17 9.38.14.png

info.plistの編集

Privacyの許可を尋ねる設定を追加する。
image.png

直接編集
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
...
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>App uses Loacation data</string>
...
</dict>
</plist>

動作確認

  1. Simulatorを起動
  2. デバッグエリアの「Simulate Location」の矢印を選択
  3. ロケーションを選択したら対応した位置情報を取得

image.png

参考文献

4
3
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
4
3