슈뢰딩거의 고등어

IOS 사용자 위치정보 얻기 본문

14일만에 IOS 앱 끝내기 챌린지

IOS 사용자 위치정보 얻기

슈뢰딩거의 고등어 2023. 4. 8. 15:21

요즘 연습 겸 따라 만들고 있는 앱이 있는데
그 앱에서 사용자의 위치를 얻어서 사용하는 기능이 있더라

 

그 기능을 만들기 위해 위치정보를 얻어올수 있는 코드를 작성해보았다.

 

간단하게 챗지피티에게 LoationView 와 LocationManager 를 만들게 하고 일부 수정한 뒤 실행해보았다.

[코드]

더보기
//
//  LocationView.swift
//  Navigation
//
//  Created by jhmin on 2023/04/08.
//

import SwiftUI

struct LocationView: View {
    
    @StateObject private var locationManager = LocationManager()
    
    var body: some View {
        VStack {
            if let location = locationManager.location {
                Text("Latitude: \(location.coordinate.latitude), Longitude: \(location.coordinate.longitude)")
                    .padding()
            } else {
                Text("Location not available")
                    .padding()
            }
        }
        .onAppear {
            locationManager.requestLocation()
        }
    }
}

struct LocationView_Previews: PreviewProvider {
    static var previews: some View {
        LocationView()
    }
}

 

//
//  LocationManager.swift
//  Navigation
//
//  Created by jhmin on 2023/04/08.
//

import Foundation
import CoreLocation
import Combine

class LocationManager: NSObject, ObservableObject {
    
    private let locationManager = CLLocationManager()
    private let geocoder = CLGeocoder()
    
    @Published var location: CLLocation? = nil
    @Published var placemark: CLPlacemark? = nil
    
    override init() {
        super.init()
        self.locationManager.delegate = self
    }
    
    func requestLocation() {
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.requestLocation()
    }
}

extension LocationManager: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        self.location = location
        self.geocoder.reverseGeocodeLocation(location) { placemarks, error in
            guard error == nil, let placemark = placemarks?.first else { return }
            self.placemark = placemark
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        if manager.authorizationStatus == .denied {
            print("Location access denied")
        } else if manager.authorizationStatus == .authorizedWhenInUse {
            self.requestLocation()
        }
    }
}

실행 결과는 

실행화면
로그

 

에러문구가 뭔소린지 모르겠어서 그대로 복사해서

챗지피티에게 물어보았다.

역시나 챗지피티 단숨에 해결방안을 내놓았다.

표시한 저 권한을 추가하고 Value 에 간략하게 위치 권한 요청 이런식으로 적어준 후

다시 시작을 하면 위치 권한요청 창이 뜬 후,

권한 허용을 해주면
만든 화면에 위치가 뜨는 것을 알 수 있다. 

실행결과

 

만약 그 후에도 안 뜬다면

시뮬레이터 설정을 확인해보자

Comments