iOS

swift - 사용자의 위치정보 얻기

유사앱등이 2022. 5. 26. 02:14

 

framework : Core Location

어플에 위치 서비스를 추가하는데 사용하는 프레임워크

 

class CLLocationManager : NSObject

CLLocationManager 클래스의 인스턴스를 사용,

어플에 사용자의 위치와 관련된 이벤트의 전달을 시작/중지하는데 사용하는 객체

 

protocol : CLLocationManagerDelegate

관련된 location manager 객체에서 이벤트를 수신하는데 사용하는 메서드

 

----

위치 서비스를 사용하기 위해, 사용자로부터 승인을 받아야 한다.

----

 

 

1. import CoreLocation

 

2. create a locationManager with CLLocationManager class

 

CLLocationManager 클래스를 사용할 뷰컨트롤러(또는 컨트롤러)에서 클래스를 생성해줌

 

let locationManager = CLLocationManager() 

// getting hold of the current GPS location of the phone.

 

 

 

3. trigger a permission request

locationManager.requestWhenInUseAuthorization()

// trigger a permission request

-> pop up on screen & ask the user for permission.

 

주의사항: CLLocationManager의 메서드를 사용하려 할 때,

다른 메서드보다 delegate를 먼저 만들어준다

locationManager.delegate = self

locationManager.requestWhenInUseAuthorization()

처럼 메서드를 이후에 작성해줘야 정상적으로 작동함

 

 

4. Info.plist(property list) - add New property 

 

위의 3번과 이어지는 내용인데, info.plist 파일에 아래와 같이 Privacy - Location... 과 관련된 항목을 새로 추가해준다.

ex)

Key : "Privacy - Location When in Use Usage Description"

Value : We need your location to get the current weather for where you are.

이 때, Value에 넣은 값은 유저에게 보여지는 메세지인데, 왜 위치정보가 필요한지 설명해주는 문구를 넣으면 됨

 

 

5. Use method of CLLocationManager class

이제 CLLocationManager의 메서드를 필요에 따라 사용해주면 됨

 

ex)

locationManager.requestLocation()

// Request the one-time delivery of the user's current location

 

++) requestLocation 메서드를 사용할 때

locationManager(_:didUpdateLocations: ), locationManager(_:didFailWithError: ) 

위의 두 메서드를 함께 사용하지 않으면 에러가 발생하게 됨

 

 

 

'iOS' 카테고리의 다른 글

iOS ) Info.plist 정리  (0) 2022.05.30
Xcode ) Storyboard - Object Library  (0) 2022.05.29
swift - Extension  (0) 2022.05.13
swift ) 진수 변환  (0) 2022.05.06
swift ) Protocol 관련 정리  (0) 2022.04.28