Machineboy空

Core Location을 파헤쳐 보자! 본문

언어/swift

Core Location을 파헤쳐 보자!

안녕도라 2024. 10. 9. 16:42

어떤 정보를 파악할 수 있을까?

  • CLLocation
    • latitude, longitude
  • CLLocationCoordinate2D
  • CLFloor
  • CLHeading

LocationManger Class를 선언하고 CLLocationMangerDelegate를 상속하는데 이의 역할이 무엇인지에 관해 읽어보면 좋을 글

 

https://zeddios.tistory.com/8

 

iOS ) 왕초보를 위한 delegate정리

swift 공부를 하면서 꼭 알아야하는 개념 중 하나가 delegate개념인데요, 저같은 경우에는 자료들도 다 영어고 한글로 된 설명을 봐도 너무 이해하기가 어렵더라구요 :( 요 며칠간 공부를 하다가 어

zeddios.tistory.com

 

import SwiftUI
import CoreLocation

/// NSObject(클래스): 어플리케이션 대부분의 객체에 필요한 기본 동작을 정의하는 클래스, 객체 초기화/ 메모리 관리/객체 비교/객체 복사
/// CLLocationManagerDelegate(프로토콜): 이벤트가 발생하면 프로토콜에 따라 대신 일을 해줄게!
/// ObservableObject(프로토콜) : 관찰하고 있다가 업테이트될 때마다 뷰를 갱신!

class LocationManager : NSObject, ObservableObject, CLLocationManagerDelegate {
    
    /// CLLocationManager(클래스): 위치정보 관련 역할을 수행해주는 클래스
    /// 우선 이 샘플에서는 상속해서 쓰지 않고 선언해서 씀
    var locationManager = CLLocationManager()
    
    @Published var authorizationStatus: CLAuthorizationStatus?  /// 위치 권한 상태
    @Published var heading: CLHeading?                          /// 방향
    
    override init() {
        super.init()
        locationManager.delegate = self
        locationManager.startUpdatingHeading()
    }
    
    /// CLLocationManagerDelegate의 함수
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        switch manager.authorizationStatus {
        case .authorizedWhenInUse, .authorizedAlways:
            authorizationStatus = manager.authorizationStatus
            locationManager.requestLocation()
        case .restricted:
            authorizationStatus = .restricted
        case .denied:
            authorizationStatus = .denied
        case .notDetermined:
            authorizationStatus = .notDetermined
            manager.requestWhenInUseAuthorization()
        default:
            break
            
        }
    }
    
    /// Location update
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locationManager.requestLocation()
    }
    
    /// heading update
    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        heading = newHeading
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error: \(error.localizedDescription)")
    }
}

extension CLLocationCoordinate2D {
    /// Returns distance from coordianate in meters.
    /// - Parameter from: coordinate which will be used as end point.
    /// - Returns: Returns distance in meters.
    ///
    func distance(from: CLLocationCoordinate2D) -> CLLocationDistance {
        let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
        let to = CLLocation(latitude: self.latitude, longitude: self.longitude)
        return from.distance(from: to)
    }
}