Storyboard
コード記述
import UIKit
import CoreLocation
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var button: UIButton!
private var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
button.layer.cornerRadius = 20.0
}
private func getCurrentLocation() {
// 緯度、経度表示用のラベル
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
let status = CLLocationManager.authorizationStatus()
switch status {
case .restricted, .denied:
print("It's denied")
break
case .notDetermined:
locationManager.delegate = self
locationManager.distanceFilter = 10
locationManager.startUpdatingLocation()
case .authorizedWhenInUse, .authorizedAlways:
locationManager.delegate = self
locationManager.distanceFilter = 10
locationManager?.startUpdatingLocation()
default:
break
}
}
@IBAction func getCurrentLocationAction(_ sender: Any) {
getCurrentLocation()
}
}
extension ViewController: CLLocationManagerDelegate {
// 緯度経度が変更された時に呼ばれる
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.first
let latitude = location?.coordinate.latitude
let longitude = location?.coordinate.longitude
print("latitude: \(latitude!)\nlongitude: \(longitude!)")
label.text = "latitude: \(latitude!)\nlongitude: \(longitude!)"
}
}
Info.plistで許可設定の追加
☆参考文献