포스트

킥보드 프로젝트 1일차

일주일간 새로운 팀프로젝트가 시작된다.

이번엔 좀 더 다양한 기능을 사용할 수 있게된 프로젝트이다.

이번에 내가 기본기능에서 담당하는건, 반납 기능이다.

반납을할때 pin을 꽂으면 될 듯 하다.

그리고 대여값에 있던 내용을 지워주면 되기에 해당기능은 얼추 진행이 되었을 때 연결하면 될 듯하다.

테스트용 지도 구현.

우선 빈프로젝트에 해당 기능을 구현해서 테스트를 하는게 바람직해 보인다.

우선 MkMapView를 UI에 그렸고,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import UIKit
import MapKit
import CoreLocation


class ViewController: UIViewController, MKMapViewDelegate {

    
    @IBOutlet weak var mapView: MKMapView!
    
    let locationManager = CLLocationManager()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
        
        mapView.delegate = self
        mapView.showsUserLocation = true
    
        
    }

    @IBAction func returnBoardBtn(_ sender: UIButton) {
    }
    
}

extension ViewController: CLLocationManagerDelegate {
 
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            locationManager.startUpdatingLocation()
            let lat = location.coordinate.latitude
            let lon = location.coordinate.longitude
            
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
        let alert = UIAlertController(title: "에러발생", message: "로드중 \(error.localizedDescription) 가 발생했습니다.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "확인", style: .default))
        self.present(alert, animated: true)
    }
    
}

우선은 다음과 같이 뼈대를 작성했다.

문제 해결

실행을 했을때 현재는 문제가 발생한다.

simulator_screenshot_ADFD43F7-4EE9-4B7F-B14B-7D7D079C4D56

현재 위치를 받아오는 과정에서 생긴 문제이다.

현재 위치를 유져의 동의 없이 이루어진듯 하다.

실제로 어플을 실행했을때 notice가 없었다.

CleanShot 2024-04-22 at 16 31 16@2x

이부분이 빠져서 생긴 문제 같다.

수정해주었다.

requestLocation() 호출 시, 현위치를 다시 가져오게 하는 기능을 구현했다.

1
2
3
4
5
6
7
8
9
10
11
12
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            
            locationManager.startUpdatingLocation()
            let lat = location.coordinate.latitude
            let lon = location.coordinate.longitude
            let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: lat, longitude: lon), span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
            
            mapView.setRegion(region, animated: true)
            mapView.showsUserLocation = true
        }
    }

위치를 업데이트 한뒤, 위도, 경도 값을 region에 저장하고 그것을 mapView에 띄우는 매커니즘으로 가게된다.

일단 시뮬레이터에 지정해둔 Location에 위치하는것까지는 구현이 되었으나.

다른 기능을 Test를 하려고하니 Error가 발생한다.

1
did fail with error: Error Domain=kCLErrorDomain Code=0 "(null)"

이제는 좌표값을 가져오는 기능을 구현해봐야 한다.

사이트를 참고 하여 위치를 가져왔다.

1
2
3
4
5
if CLLocationManager.locationServicesEnabled() {
                self?.locationManager.requestWhenInUseAuthorization()
                let currentLocation = self?.locationManager.location
                print(currentLocation)
            }

이떄 main thread에서는 실행하면 안된다는 error가 뜨므로,

global로 바꿔주면

1
2
3
4
5
6
7
8
9
10
11
 @IBAction func returnBoardBtn(_ sender: UIButton) {
        DispatchQueue.global().async { [weak self] in
            if CLLocationManager.locationServicesEnabled() {
                self?.locationManager.requestWhenInUseAuthorization()
                let currentLocation = self?.locationManager.location
                print(currentLocation)
            }
            
        }
        
    }

버튼을 클릭했을때 그 위치에 핀을 꽂게 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@IBAction func returnBoardBtn(_ sender: UIButton) {
        DispatchQueue.global().async { [weak self] in
            if CLLocationManager.locationServicesEnabled() {
                self?.locationManager.requestWhenInUseAuthorization()
                let currentLocation = self?.locationManager.location
                
                self?.addMark(coordinate: CLLocationCoordinate2D(latitude: currentLocation?.coordinate.latitude ?? 37.503702192, longitude: currentLocation?.coordinate.longitude ?? 127.025313873406))
            }
            
        }
        
    }
    
    func addMark(coordinate: CLLocationCoordinate2D) {
        let pin = MKPointAnnotation()
        pin.coordinate = coordinate
        mapView.addAnnotation(pin)
    }

Apr-22-2024 18-33-28

끝.

나중에 coredata가 연결되면, 그때 등록을 하면 될 것 같다.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.