3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SwiftUI でGPSから現在地を取得

Last updated at Posted at 2021-05-31

概要

GPS情報を使うアプリを作りたいので
SwiftUIで現在地を取得するだけの最も単純なサンプルを作成してみた。

CoreLocationサービスを使うための準備

アプリの info.plist の
Information Property List
Privacy - Location When In Use Usage Description
を追加し、
「現在位置を取得するために使います」
といった適当な文字列を設定する。

ソースコード

LocationManager.swiftファイルを追加してlocation情報を @Published で発行する
ContentView.swift 内で観測オブジェクト LocationManager からlocation情報を取り出して表示する。

LocationManager.swift
import MapKit

class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    let manager = CLLocationManager()
    @Published var location = CLLocation()
    
    override init() {
        super.init()
        
        self.manager.delegate = self
        self.manager.requestWhenInUseAuthorization()
        self.manager.desiredAccuracy = kCLLocationAccuracyBest
        self.manager.distanceFilter = 2
        self.manager.startUpdatingLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, 
                           didUpdateLocations locations: [CLLocation]) {
        self.location = locations.last!
    }
    
}

LocationManagerクラスが発行した locationを取り出して画面上に表示する

ContentView.swift

import SwiftUI

struct ContentView: View {
    @ObservedObject var manager = LocationManager()
    
    var body: some View {
        let latetude = $manager.location.wrappedValue.coordinate.latitude
        let longitude = $manager.location.wrappedValue.coordinate.longitude
        Text("\(latetude), \(longitude)").padding()    
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

感想

R03/05/31

MapKitや LocationManager よりも SwiftUIに慣れる必要がありそう

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?