Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[iOS] 여정 드로잉에 필요한 filter를 평균값을 활용하도록 수정 #315

Merged
merged 14 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,8 @@ extension HomeViewController: RecordJourneyButtonViewDelegate {

let refreshButtonAction = UIAction { [weak self] _ in
guard let coordinates = self?.contentViewController.visibleCoordinates else { return }

self?.contentViewController.clearAnnotations()
self?.contentViewController.clearOverlays()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분 지우고 ViewModel 쪽에서

 case .refreshButtonDidTap(visibleCoordinates: (let minCoordinate, let maxCoordinate)):
            self.state.isRefreshButtonHidden.send(true)
            self.fetchJourneys(minCoordinate: minCoordinate, maxCoordinate: maxCoordinate)
            self.state.overlaysShouldBeCleared.send(true) // 👍

이렇게 호출해서 방식을 통일시켜주는 것이 더 좋을 것 같습니다.

self?.viewModel.trigger(.refreshButtonDidTap(visibleCoordinates: coordinates))
}
self.refreshButton.addAction(refreshButtonAction, for: .touchUpInside)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,20 +320,14 @@ extension MapViewController: CLLocationManagerDelegate {
return
}

let previousCoordinate = (self.viewModel as? RecordJourneyViewModel)?.state.previousCoordinate.value

if let previousCoordinate = previousCoordinate {
if !self.isDistanceOver5AndUnder50(coordinate1: previousCoordinate,
coordinate2: newCurrentLocation.coordinate) {
return
}
}

let coordinate2D = CLLocationCoordinate2D(latitude: newCurrentLocation.coordinate.latitude,
longitude: newCurrentLocation.coordinate.longitude)
recordJourneyViewModel.trigger(.fiveLocationsDidRecorded(coordinate2D))

recordJourneyViewModel.trigger(.locationDidUpdated(coordinate2D))
recordJourneyViewModel.trigger(.locationsShouldRecorded([coordinate2D]))
// filtering된 위치 정보가 있을 경우(5개의 위치 데이터가 들어와 필터링이 완료되었을 경우)에만 아래 두 trigger 실행 가능
guard let filteredCoordinate2D = recordJourneyViewModel.state.filteredCoordinate.value else { return }
recordJourneyViewModel.trigger(.locationDidUpdated(filteredCoordinate2D))
recordJourneyViewModel.trigger(.locationsShouldRecorded([filteredCoordinate2D]))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분은 state의 값을 가져와서 다시 trigger 할거라면
이 부분이 아니라 다른 ViewModel 내부나 bind 함수쪽에서 하는 것이 더 좋아보입니다.

}

private func handleAuthorizationChange(_ manager: CLLocationManager) {
Expand Down Expand Up @@ -374,13 +368,13 @@ extension MapViewController: CLLocationManagerDelegate {
}
}

private func isDistanceOver5AndUnder50(coordinate1: CLLocationCoordinate2D,
coordinate2: CLLocationCoordinate2D) -> Bool {
let location1 = CLLocation(latitude: coordinate1.latitude, longitude: coordinate1.longitude)
let location2 = CLLocation(latitude: coordinate2.latitude, longitude: coordinate2.longitude)
MSLogger.make(category: .navigateMap).log("이동한 거리: \(location1.distance(from: location2))")
return 5 <= location1.distance(from: location2) && location1.distance(from: location2) <= 50
}
// private func isDistanceOver5AndUnder50(coordinate1: CLLocationCoordinate2D,
// coordinate2: CLLocationCoordinate2D) -> Bool {
// let location1 = CLLocation(latitude: coordinate1.latitude, longitude: coordinate1.longitude)
// let location2 = CLLocation(latitude: coordinate2.latitude, longitude: coordinate2.longitude)
// MSLogger.make(category: .navigateMap).log("이동한 거리: \(location1.distance(from: location2))")
// return 5 <= location1.distance(from: location2) && location1.distance(from: location2) <= 50
// }

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,16 @@ public final class RecordJourneyViewModel: MapViewModel {
case locationDidUpdated(CLLocationCoordinate2D)
case locationsShouldRecorded([CLLocationCoordinate2D])
case recordingDidCancelled
case fiveLocationsDidRecorded(CLLocationCoordinate2D)
}

public struct State {
// CurrentValue
public var previousCoordinate = CurrentValueSubject<CLLocationCoordinate2D?, Never>(nil)
public var currentCoordinate = CurrentValueSubject<CLLocationCoordinate2D?, Never>(nil)
public var recordingJourney: CurrentValueSubject<RecordingJourney, Never>
public var recordedCoordinates = CurrentValueSubject<[CLLocationCoordinate2D], Never>([])
public var filteredCoordinate = CurrentValueSubject<CLLocationCoordinate2D?, Never>(nil)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

filteredCoordinate는 5번 찍힐 때마다 단순히 값을 전달만 하는 것 같은데 맞을까요?
그렇다면 PassthroughSubject를 사용하는 것이 더 적절한 것 같은데 어떨까요?

}

// MARK: - Properties
Expand Down Expand Up @@ -54,10 +57,14 @@ public final class RecordJourneyViewModel: MapViewModel {
#if DEBUG
MSLogger.make(category: .home).debug("View Did load.")
#endif

/// 이전 currentCoordinate를 previousCoordinate에, 저장할 현재 위치를 currentCoordinate에 update
case .locationDidUpdated(let coordinate):
let previousCoordinate = self.state.currentCoordinate.value
self.state.previousCoordinate.send(previousCoordinate)
self.state.currentCoordinate.send(coordinate)

/// 저장하고 자 하는 위치 데이터를 서버에 전송
case .locationsShouldRecorded(let coordinates):
Task {
let recordingJourney = self.state.recordingJourney.value
Expand All @@ -67,10 +74,12 @@ public final class RecordJourneyViewModel: MapViewModel {
switch result {
case .success(let recordingJourney):
self.state.recordingJourney.send(recordingJourney)
self.state.filteredCoordinate.send(nil)
case .failure(let error):
MSLogger.make(category: .home).error("\(error)")
}
}
/// 기록 중에 여정 기록을 취소
case .recordingDidCancelled:
Task {
guard let userID = self.userRepository.fetchUUID() else { return }
Expand All @@ -86,7 +95,72 @@ public final class RecordJourneyViewModel: MapViewModel {
MSLogger.make(category: .home).error("\(error)")
}
}
/// 업데이트되는 위치 정보를 받아와 5개가 될 경우 평균값 필터링 후 저장하는 로직
case .fiveLocationsDidRecorded(let coordinate):
self.filterLongestCoordinate(coordinate: coordinate)
}
}

}

private extension RecordJourneyViewModel {

func calculateDistance(from coordinate1: CLLocationCoordinate2D,
to coordinate2: CLLocationCoordinate2D) -> CLLocationDistance {
let location1 = CLLocation(latitude: coordinate1.latitude,
longitude: coordinate1.longitude)
let location2 = CLLocation(latitude: coordinate2.latitude,
longitude: coordinate2.longitude)
return location1.distance(from: location2)
}

func filterLongestCoordinate(coordinate: CLLocationCoordinate2D) {
if let previousCoordinate = self.state.previousCoordinate.value {
if calculateDistance(from: previousCoordinate, to: coordinate) <= 5 {
return
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if let previousCoordinate = self.state.previousCoordinate.value {
if calculateDistance(from: previousCoordinate, to: coordinate) <= 5 {
return
}
}
if let previousCoordinate = self.state.previousCoordinate.value,
calculateDistance(from: previousCoordinate, to: coordinate) <= 5 {
return
}

var recordedCoords = self.state.recordedCoordinates.value
recordedCoords.append(coordinate)
self.state.recordedCoordinates.send(recordedCoords)

if self.state.recordedCoordinates.value.count >= 5 {
let initialCoordinate = recordedCoords.reduce(CLLocationCoordinate2D(latitude: 0,
longitude: 0)) { result, coordinate in
return CLLocationCoordinate2D(latitude: result.latitude + coordinate.latitude,
longitude: result.longitude + coordinate.longitude)
}
let initialLat = initialCoordinate.latitude
let initialLong = initialCoordinate.longitude
let averageCoordinate = CLLocationCoordinate2D(latitude: initialLat / Double(recordedCoords.count),
longitude: initialLong / Double(recordedCoords.count))

// 가장 먼 거리에 있는 Coordinate의 index값을 찾음.
guard let indexToRemove = recordedCoords.enumerated().max(by: {
let distance1 = calculateDistance(from: $0.element,
to: averageCoordinate)
let distance2 = calculateDistance(from: $1.element,
to: averageCoordinate)
return distance1 < distance2
})?.offset else {
return
}

var fourCoordinates = recordedCoords
fourCoordinates.remove(at: indexToRemove)

let finalCoordinate = fourCoordinates.reduce(CLLocationCoordinate2D(latitude: 0,
longitude: 0)) { result, coordinate in
return CLLocationCoordinate2D(latitude: result.latitude + coordinate.latitude,
longitude: result.longitude + coordinate.longitude)
}
let finalLat = finalCoordinate.latitude
let finalLong = finalCoordinate.longitude
let finalAverage = CLLocationCoordinate2D(latitude: finalLat / Double(fourCoordinates.count),
longitude: finalLong / Double(fourCoordinates.count))

self.state.filteredCoordinate.send(finalAverage)
self.state.recordedCoordinates.send([])
}
}
}