티스토리 뷰
이번에는 사용자의 위치 정보를 가져와 볼까합니다.
실제 가져오는 값은 위도와 경도 이고 추가로 얻을 수 있는 정보인 사용자의 실시간 속도까지 알아보도록 하겠습니다.
(참고로 여기서 속도는 m/s 입니다. )
그 전에 추가를 해줘야 사용할 수 있겠죠?
(해당 기능은 pod 가 필요없는 자체 기능입니다.)
import CoreLocation
그리고 사용자의 위치정보를 위한 권한을 추가해야겠죠?
참고로 맨위에 있는 When In Use 는 반드시 추가해주세요.
* 기본 셋팅
import CoreLocation
class LocationViewController: UIViewController, CLLocationManagerDelegate {
var mapManager : CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mapManager = CLLocationManager()
mapManager.delegate = self
mapManager.requestWhenInUseAuthorization() // 권한 없을시 요청
mapManager.desiredAccuracy = kCLLocationAccuracyBest //정확도
mapManager.startUpdatingLocation() // 위치 수집 시작
if mapManager.authorizationStatus == .denied {
print("권한을 거절당한 상태입니다.")
}
}
}
위 코드까지 넣고 실행 하시면 아래처럼 권한 요청 창이 뜨게 됩니다.
이제 준비는 끝났는데
저희가 화면을 보는 동안 계속 정보가 업데이트가 되는 것이 좋겠죠?
그래서 저희는 화면에 UILabel 을 추가하고 Timer를 통해 업데이트 하는 방식을 사용하겠습니다.
아래 두개의 코드를 추가해 주세요.
//viewDidLoad 마지막 부분에 추가해주세요.
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateUserInfo), userInfo: nil, repeats: true)
// 1초마다 업데이트 하는 식인데
//더 자주하고싶으신 분들은 1.0 을 더 작게 해주시면 됩니다.
func getLocation() -> (Double,Double) { // 위도 경도 뽑기
mapManager.startUpdatingLocation()
let coor = mapManager.location?.coordinate
let lat = coor?.latitude
let long = coor?.longitude
return (lat ?? 0.0,long ?? 0.0)
}
func getSpeed() -> Double { //속도뽑기
return mapManager.location?.speed ?? 0.0
}
@objc func updateUserInfo(){
userLocationLbl.text = "위치 : \(getLocation())"
speedLbl.text = "speed: \(getSpeed())"// meter/sec
}
이제 이상태로 실행하시면 아래처럼 출력되게 됩니다.
참고로 여기 속도를 보시면 -1 로 나오는데 측정이 불가능한 경우 -1 로 나온다고 하네요.
이거 지금 제가 앉아 있는 상태에서 출력해서 그런걸로 보입니다;;
실제로 폰들고 나가서 걸으시면 숫자가 바뀌게 됩니다.
(저기 표시되는 속도는 참고로 실시간 속도를 의미합니다.)
* 전체코드
import Foundation
import UIKit
import CoreLocation
class LocationViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var userLocationLbl: UILabel!
@IBOutlet weak var speedLbl: UILabel!
var mapManager : CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mapManager = CLLocationManager()
mapManager.delegate = self
mapManager.requestWhenInUseAuthorization() // 권한 없을시 요청
mapManager.desiredAccuracy = kCLLocationAccuracyBest //정확도
mapManager.startUpdatingLocation() // 위치 수집 시작
if mapManager.authorizationStatus == .denied {
print("권한을 거절당한 상태입니다.")
}
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateUserInfo), userInfo: nil, repeats: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func getLocation() -> (Double,Double) { // 위도 경도 뽑기
mapManager.startUpdatingLocation()
let coor = mapManager.location?.coordinate
let lat = coor?.latitude
let long = coor?.longitude
return (lat ?? 0.0,long ?? 0.0)
}
func getSpeed() -> Double {
return mapManager.location?.speed ?? 0.0
}
@objc func updateUserInfo(){
userLocationLbl.text = "위치 : \(getLocation())"
speedLbl.text = "speed: \(getSpeed())"// meter/sec
}
}
누군가에게 도움이되길 바라며
오늘도 파이팅입니다!
'iOS개발 > Swift 기능' 카테고리의 다른 글
Swift Charts 숫자(값) 표시 바꾸기 (Formatter) (0) | 2023.01.09 |
---|---|
Swift 해 일출 / 일몰 시간 계산식 (0) | 2022.12.27 |
Swift 달력(FSCalendar) 만들기 (0) | 2022.12.07 |
Swift DropDown 메뉴 만들기 (0) | 2022.12.05 |
Swift Lottie 로 움직이는 사진 넣기 (0) | 2022.12.01 |
댓글