💬
SwiftUIで位置情報をコンソールに出力する
iPhoneアプリ開発初心者です。
Swift UIのサンプルコードが少なかったので、メモ程度に。GitHubにもあとで公開します。
TL;DR;
- CoreLocationを追加
- info.plistにPrivacyを設定
- UIApplicationDelegateAdaptorを設定
環境
- Mac OS X 10.15.7
- Xcode 12.3
CoreLocationを追加
Targets > Build Phases > Link Binaries with LibrariesにCoreLocationを追加する。
参考
info.plistにPrivacyを設定
アプリ起動時に位置情報を使用してよいか尋ねるようになる。
UIApplicationDelegateAdaptorを設定
GPSSampleApp.swiftにUIApplicationDelegateAdaptorを設定。
import SwiftUI
import CoreLocation
@main
struct GPSSampleApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var locationManager : CLLocationManager?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
locationManager = CLLocationManager()
locationManager!.delegate = self
locationManager!.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager!.desiredAccuracy = kCLLocationAccuracyBest
locationManager!.distanceFilter = 10
locationManager!.activityType = .fitness
locationManager!.startUpdatingLocation()
}
return true
}
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)
}
}
参考
Discussion