CoreLocationで現在位置を取得する
現在位置の取得はこちらの記事にまとめられていたんですがSwift3.0とだいぶ古いのと余計なUIが混ざっていてわかりにくいのでシンプルに作り直しました。
import UIKit
import CoreLocation
class ViewController: UIViewController {
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
manager.requestWhenInUseAuthorization()
case .restricted, .denied:
break
case .authorizedAlways, .authorizedWhenInUse:
manager.startUpdatingLocation()
locationManager.startUpdatingLocation()
default:
break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
return
}
let coordinate = location.coordinate
print("緯度: \(coordinate.latitude), 経度: \(coordinate.longitude)")
}
}