MangDic
MangDic_IOS
MangDic
전체 방문자
오늘
어제
  • 분류 전체보기
    • iOS
      • RxSwift
      • Firebase
      • 오픈소스
      • 기술?
      • 디자인패턴
      • 에러노트
      • 자료구조
    • 네트워크
    • 알고리즘
      • 해시
      • 정렬
      • DFS
      • 스택
    • CS
    • 알아두면 좋아!

인기 글

티스토리

hELLO · Designed By 정상우.
MangDic

MangDic_IOS

swift - CoreLocation을 사용해서 현재 위치(위도, 경도) 가져오기
iOS/기술?

swift - CoreLocation을 사용해서 현재 위치(위도, 경도) 가져오기

2021. 11. 15. 17:55

프로젝트를 하던 중 현재 위치를 사용해야 할 일이 생겼다!

 

kakaoLocal API 등이 있지만, 일단은 현재 위치만 가져오면 되기 때문에 CoreLocation을 사용하기로 했습니다.

 

먼저 Info.plist로 달려갑니다.

현재 위치사용 동의를 구하는 내용을 추가해 줍니다

Privacy - Location When In Use Usage Description를 추가하고 보여줄 Value를 적으면 돼요!

 

 

// ViewController.swift

import UIKit
import CoreLocation

class ConfusionViewController: UIViewController, CLLocationManagerDelegate {

	var locationManager = CLLocationManager()
    
    ...
    
}

CoreLocation를 import 해주고, CLLocationManagerDelegate 프로토콜을 채택합니다.

그 후에 CLLocationManager를 정의합시당

 

 

fileprivate func setLocationManager() {
    // 델리게이트를 설정하고,
    locationManager.delegate = self
    // 거리 정확도
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    // 위치 사용 허용 알림
    locationManager.requestWhenInUseAuthorization()
    // 위치 사용을 허용하면 현재 위치 정보를 가져옴
    if CLLocationManager.locationServicesEnabled() {
       locationManager.startUpdatingLocation()
    }
    else {
        print("위치 서비스 허용 off")
    }
}

viewDidLoad에서 해도 되지만, 따로 함수를 만들어서 세팅했습니다.

 

마지막으로 현재 위치를 가져오는 메소드를 작성하면 끝!!

 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        print("위치 업데이트!")
        print("위도 : \(location.coordinate.latitude)")
        print("경도 : \(location.coordinate.longitude)")
    }
}
    
// 위치 가져오기 실패
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("error")
}

 

실행을 해보면...

 

설정한 대로 위치 사용에 동의하냐는 내용이 나오죠??

여기서 수락을 누르면!

 

 

짠~

시뮬레이터로 돌려서 이상한 값이 나오지만, 폰으로 직접 돌리면 제대로 가져옵니다 ㅎㅎ

'iOS > 기술?' 카테고리의 다른 글

swift - 네이버맵 연동하기 (지도 띄우기)  (0) 2023.05.02
swift - SnapKit & Then  (0) 2022.08.10
swift - ReactorKit  (0) 2022.05.04
swift - 카카오맵 API 연동하기  (3) 2021.11.17
swift - 컬렉션뷰 버튼 토글하기!  (0) 2021.11.11
    'iOS/기술?' 카테고리의 다른 글
    • swift - SnapKit & Then
    • swift - ReactorKit
    • swift - 카카오맵 API 연동하기
    • swift - 컬렉션뷰 버튼 토글하기!
    MangDic
    MangDic
    IOS

    티스토리툴바