💬

SwiftUIで位置情報をコンソールに出力する

2021/02/11に公開

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を追加する。

参考
https://i-app-tec.com/ios/core-location.html

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)

    }
    
}

参考
https://qiita.com/antk/items/4bd97f0baa770ecef870
https://qiita.com/peter_parker/items/0ec7fce46b23ddc1b589
https://qiita.com/eito_2/items/7e7d0b658f2bcda3897e
https://github.com/vyeah321/Location/blob/master/Location/ViewController.swift
https://qiita.com/vyeah321/items/ec01530012b5b3020301

実行結果

Discussion