🧐 현재 위치를 가져오는 작업을 간략히 정리해봤습니다.
Step 1
Info.plist 에서 권한을 설정해주셔야합니다.
🍁 Privacy - Location 속성
Step 2
위치 정보를 가져오기 위해 ViewController에 CoreLocation 을 import 하고 CLLocationManagerDelegate Extension 시키키
🍁 ViewController.swift
import CoreLocation
...
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
locationManager.stopUpdatingLocation()
let lat = location.coordinate.latitude
let lon = location.coordinate.longitude
print("Latitude: \(lat)\nLongitude: \(lon)")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error: \(error.localizedDescription)")
}
}
Step 3
CLLocationManager를 선언하고 viewDidLoad를 통하여 위치 서비스에 대한 권한을 요청하고 현재 위치 정보를 가져오게 하기
🍁 ViewController.swift
class ViewController: UIViewController {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .systemBackground
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization() // 위치 서비스를 사용하기 위한 사용자 권한 요청
locationManager.requestLocation() // 사용자의 현재 위치에 대한 일회성 전달을 요청
}
}