iOS, CoreLocation_위치 가져오기

iDO·2021년 10월 18일
0

iOS

목록 보기
2/8
post-thumbnail

🧐 현재 위치를 가져오는 작업을 간략히 정리해봤습니다.

Step 1

Info.plist 에서 권한을 설정해주셔야합니다.

🍁 Privacy - Location 속성

Privacy - Location Always and When In Use Usage... : 앱이 항상 사용자의 위치 정보에 대한 엑세스를 요청하는 이유를 알려주는 메시지
Privacy - Location Always Default Accuracy Reduced : 앱이 기본적으로 축소된 위치 정확도를 요청하는지 여부를 나타내는 Bool 값
Privacy - Location Temporary Usage Description D... : 앱이 일시적으로 사용자의 위치 정보에 대한 엑세스를 요청하는 이유를 알려주는 메시지
Privacy - Location Usage Description : 앱이 사용자의 위치 정보에 대한 엑세스를 요청하는 이유를 알려주는 메시지
Privacy - Location When In Use Usage Description : 앱이 포그라운드에서 실행되는 동안 앱이 사용자의 위치 정보에 대한 액세스를 요청하는 이유를 알려주는 메시지
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() // 사용자의 현재 위치에 대한 일회성 전달을 요청
    }

}
profile
이곳은 저를 위한 iOS 설명서입니다.

0개의 댓글