概要
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に慣れる必要がありそう