diff --git a/Projects/Features/DrugIdentificationFeature/Sources/DrugIdentificationScene/Coordinator/DrugIdentificationCoordinator.swift b/Projects/Features/DrugIdentificationFeature/Sources/DrugIdentificationScene/Coordinator/DrugIdentificationCoordinator.swift index 577cf322..7ac39842 100644 --- a/Projects/Features/DrugIdentificationFeature/Sources/DrugIdentificationScene/Coordinator/DrugIdentificationCoordinator.swift +++ b/Projects/Features/DrugIdentificationFeature/Sources/DrugIdentificationScene/Coordinator/DrugIdentificationCoordinator.swift @@ -37,7 +37,12 @@ public final class DrugIdentificationCoordinator: BaseCoordinator { pillTabObserver = NotificationCenter.default.addObserver( forName: .pillTabSelected, object: nil, queue: .main ) { [weak self] _ in - self?.presentCameraIfAppropriate() + guard let self else { return } + // 진입 시 잔여 조회 (spec: §식별 횟수 제한 "첫 실행·재설치·화면 진입 시 표시값의 기준"). + // 조회 전용이라 카운트는 늘지 않는다(NM-331). 홈이 viewWillAppear 마다 하는 것과 같은 + // 이유로, 홈을 거치지 않고 탭으로 바로 들어온 경우에도 값을 최신으로 만든다. + self.pillUseCase.fetchPillUsage() + self.presentCameraIfAppropriate() } } @@ -49,6 +54,27 @@ public final class DrugIdentificationCoordinator: BaseCoordinator { private func presentCameraIfAppropriate() { guard navigationController.presentedViewController == nil, navigationController.viewControllers.count <= 1 else { return } + + /* + 진입 게이트 (spec: feature/pill-recognition/README.md §식별 횟수 제한 §흐름 규칙 + "식별 진입 시점(홈 '알약 식별' 카드/탭)에 … 0이면 안내 팝업을 띄우고 진입하지 않는다"). + + 홈 카드는 HomeViewModel 이 같은 규칙으로 막는데 **탭 경로에만 게이트가 없어서**, + 탭으로 들어오면 0회여도 촬영까지 그대로 진행됐다. + + 값을 모르면 통과한다 — 최종 판정은 서버 429 다(spec: "잔여 미확인 시 통과"). + + 막을 때는 홈으로 되돌린다. 알약 탭 루트는 **카메라가 덮는 걸 전제로 한 빈 화면**이라 + 그대로 두면 흰 화면만 남는다. spec 흐름도도 팝업 확인 뒤를 홈으로 둔다(P -->|확인| H). + (미리보기에서 막힌 경우는 반대로 화면을 유지한다 — 거긴 찍은 사진이 있고, 잔여 0회를 + 경고색으로 보여 주는 자리다.) + */ + if let usage = pillUseCase.pillUsage.value, usage.isExhausted { + NotificationCenter.default.post(name: .selectHomeTab, object: nil) + presentLimitAlert(usage: usage) + return + } + cameraPicker.present(from: navigationController, source: .camera) } @@ -112,7 +138,8 @@ public final class DrugIdentificationCoordinator: BaseCoordinator { // 세션 중 소진 방어: 진입 후 마지막 횟수를 쓰고 돌아온 경우, 요청을 보내지 않는다. // 값을 모르면 통과 — 최종 판정은 서버 429다 (NM-323). if let usage = self.pillUseCase.pillUsage.value, usage.isExhausted { - self.exitToHomeWithLimitAlert(usage: usage) + // 이미 미리보기에 서 있다 — 화면을 그대로 두고 팝업만 띄운다. + self.presentLimitAlert(usage: usage) return } @@ -124,20 +151,19 @@ public final class DrugIdentificationCoordinator: BaseCoordinator { navigationController.pushViewController(vc, animated: true) } - /// 한도에 걸리면 홈으로 되돌리고 안내 팝업을 띄운다. + /// 한도 안내 팝업 — **확인 뒤 미리보기에 머무른다**. 찍은 사진을 잃지 않는다 + /// (spec: feature/pill-recognition/README.md §식별 횟수 제한 "확인 시 현재 화면에 머무른다"). /// - /// 미리보기에 남겨두면 재촬영·이 사진 사용 둘 다 다시 막혀 막다른 길이 된다. - /// 요청 전에 막힌 경우(게이트)와 서버가 거절한 경우(429)를 사용자는 구분할 수 없으므로 - /// 두 경로의 동작을 통일한다. + /// 예전엔 홈으로 내보내 사진이 날아갔다. "미리보기에 남겨두면 재촬영·이 사진 사용 둘 다 + /// 다시 막혀 막다른 길" 이라는 게 이유였지만, 미리보기는 남은 횟수를 0회·경고색으로 + /// 표시하므로 막다른 길이 아니라 **왜 막혔는지 보이는 자리**다. 사진을 버리는 대가로 + /// 얻는 게 없다 — 다시 찍으려면 촬영부터 다시 해야 한다. /// /// **여기서는 계측하지 않는다.** `pill_limit_reached` 는 한도를 실제로 소진하는 순간 /// (마지막 1회를 쓴 요청의 성공 응답)에 `DrugIdentificationViewModel` 이 발사한다 — /// 막힌 시도를 세면 재시도하지 않은 사용자가 빠지고 재시도한 사용자는 중복으로 잡힌다. - private func exitToHomeWithLimitAlert(usage: PillUsageModel?) { - navigationController.popToRootViewController(animated: false) - NotificationCenter.default.post(name: .selectHomeTab, object: nil) - - // 탭 전환 뒤에도 보이도록 윈도우 위에 띄운다. + private func presentLimitAlert(usage: PillUsageModel?) { + // 루트(네비게이션 컨트롤러) 뷰에 붙으므로 push·pop 과 무관하게 남는다. DSAlertCardView.presentOverWindow( title: PillLimitAlertText.title, message: PillLimitAlertText.message(resetAt: usage?.resetAt) @@ -147,6 +173,15 @@ public final class DrugIdentificationCoordinator: BaseCoordinator { // MARK: - ④ 로딩 → ⑤/⑥/⑦ private func startIdentification(image: UIImage) { + navigationController.pushViewController(makeLoadingVC(image: image), animated: true) + } + + /// 로딩 화면 + 분석 VM 한 벌. + /// + /// 최초 진입은 push 로, **실패 후 재시도는 실패 화면과 replace** 해서 쓴다 — + /// 재시도가 같은 사진으로 분석을 처음부터(온디바이스 탐지 + 서버 왕복) 다시 돌려야 하는데, + /// VM 은 이미 종료 상태를 방출한 뒤라 재사용할 수 없다. + private func makeLoadingVC(image: UIImage) -> PillLoadingVC { let viewModel = DrugIdentificationViewModel(image: image) let loadingVC = PillLoadingVC(image: image, viewModel: viewModel) @@ -162,14 +197,19 @@ public final class DrugIdentificationCoordinator: BaseCoordinator { } loadingVC.onFailure = { [weak self, weak loadingVC] message in guard let loadingVC else { return } - self?.showFailure(message: message, replacing: loadingVC) + self?.showFailure(message: message, image: image, replacing: loadingVC) } // 한도 도달은 실패가 아니다 — 미리보기로 되돌리고 안내 팝업만 띄운다. loadingVC.onLimitExceeded = { [weak self] usage in - self?.exitToHomeWithLimitAlert(usage: usage) + guard let self else { return } + // 로딩 화면은 머무를 수 있는 자리가 아니다 — 나갈 버튼이 없다(PillLoadingVC 가 숨긴다). + // 사진을 고른 미리보기로 되돌려, 게이트로 막힌 경우와 같은 자리에서 같은 팝업을 띄운다 + // (spec: "요청이 429 로 거부된 경우도 같은 팝업으로 처리한다"). + self.navigationController.popViewController(animated: true) + self.presentLimitAlert(usage: usage) } - navigationController.pushViewController(loadingVC, animated: true) + return loadingVC } // MARK: - ⑤ 인식 결과 @@ -354,14 +394,26 @@ public final class DrugIdentificationCoordinator: BaseCoordinator { /// - Parameter message: 서버가 준 실패 사유. 화면이 그대로 띄운다 — 예전엔 여기서 버려져 /// 네트워크와 무관한 오류(App Check 실패 등)도 "네트워크 연결을 확인하라"고 안내됐다. - private func showFailure(message: String?, replacing loadingVC: UIViewController) { + private func showFailure(message: String?, image: UIImage, replacing loadingVC: UIViewController) { let vc = AnalysisFailedVC(message: message) - // 네비바 뒤로·푸터 '뒤로' 모두 홈으로 — 이 화면엔 돌아갈 이전 단계가 없다. - vc.onBackTapped = { [weak self] in self?.exitToHome() } - vc.onBack = { [weak self] in self?.exitToHome() } - vc.onRetry = { [weak self] in - self?.navigationController.popViewController(animated: true) + + /* + 두 버튼 모두 spec 의 분기를 따른다 (spec: feature/pill-recognition/README.md §식별 → 인식 결과). + + E -->|재시도| B 재시도는 **인식으로 되돌아간다** — 같은 사진으로 다시 분석 + E -->|뒤로| X 뒤로는 **촬영/미리보기로 복귀** + + 예전엔 둘 다 어긋나 있었다. 재시도가 pop 이라 사실상 spec 의 '뒤로' 였고, 뒤로는 + 홈으로 나가 버려 사진을 다시 고를 기회 없이 흐름이 끊겼다("돌아갈 이전 단계가 없다"고 + 적혀 있었지만, showPreview 가 push 한 PhotoPreviewVC 가 스택에 그대로 남아 있다). + */ + vc.onBackTapped = { [weak self] in self?.navigationController.popViewController(animated: true) } + vc.onBack = { [weak self] in self?.navigationController.popViewController(animated: true) } + vc.onRetry = { [weak self, weak vc] in + guard let self, let vc else { return } + self.replace(vc, with: self.makeLoadingVC(image: image)) } + replace(loadingVC, with: vc) } diff --git a/Projects/Features/DrugIdentificationFeature/Sources/DrugIdentificationScene/ViewModel/DrugIdentificationViewModel.swift b/Projects/Features/DrugIdentificationFeature/Sources/DrugIdentificationScene/ViewModel/DrugIdentificationViewModel.swift index 0f6ef4bb..65eab3af 100644 --- a/Projects/Features/DrugIdentificationFeature/Sources/DrugIdentificationScene/ViewModel/DrugIdentificationViewModel.swift +++ b/Projects/Features/DrugIdentificationFeature/Sources/DrugIdentificationScene/ViewModel/DrugIdentificationViewModel.swift @@ -80,7 +80,7 @@ public final class DrugIdentificationViewModel { do { segmentor = try RFDetrSegmentor() } catch { - self.emit(.failure(message: error.localizedDescription)) + self.reportSegmentationFailure(error, stage: "load") return } @@ -99,7 +99,7 @@ public final class DrugIdentificationViewModel { self.pending = (pills, self.buildItems(from: pills)) self.requestAttributes(items: self.pending?.items ?? []) } catch { - self.emit(.failure(message: error.localizedDescription)) + self.reportSegmentationFailure(error, stage: "inference") } } } @@ -136,6 +136,28 @@ public final class DrugIdentificationViewModel { } } + /* + 온디바이스 세그멘테이션 실패 — 화면엔 우리 문구, 원문은 Crashlytics 로. + + 예전엔 `error.localizedDescription` 을 그대로 띄웠다. CoreML 에러는 영문 시스템 + 메시지라 한국어 앱에 이런 문장이 그대로 나갔다: + + Failed to build the model execution plan using a model architecture file + .../rfdetr_seg_small_fp32.mlmodelc/model.mil with error code: -5 + + 실제로 배포 빌드에서 났던 문구다(CI 체크아웃에 `lfs: true` 가 빠져 모델 가중치가 + 포인터 파일로 번들된 사고). 사용자가 읽고 할 수 있는 일이 없는데다, 원인은 원인대로 + 화면에서 휘발됐다 — 로컬 빌드는 멀쩡해서 네트워크 문제로 오인하기 쉬운 부류다. + + 그래서 **화면과 로그를 가른다.** 화면은 다음에 뭘 하면 되는지만 말하고, 원문은 + Crashlytics 비치명적 이슈로 남겨 다음에 같은 사고가 나면 원인이 보이게 한다. + */ + private func reportSegmentationFailure(_ error: Error, stage: String) { + FirebaseService.log("pill segmentation failed (stage: \(stage))") + FirebaseService.recordError(error) + emit(.failure(message: "사진을 분석하지 못했어요. 잠시 후 다시 시도해 주세요.")) + } + private func requestAttributes( items: [(pillId: String, croppedImage: String)] ) { diff --git a/Projects/Modules/Networks/Sources/Foundation/BaseError.swift b/Projects/Modules/Networks/Sources/Foundation/BaseError.swift index 5199d03b..33cb3710 100644 --- a/Projects/Modules/Networks/Sources/Foundation/BaseError.swift +++ b/Projects/Modules/Networks/Sources/Foundation/BaseError.swift @@ -29,11 +29,18 @@ public enum APIError: Error, Equatable { case network(statusCode: Int, error: NetworkError) case unknown case tokenReissuanceFailed + /// 요청이 서버에 닿지도 못했다(기내모드·권역 이탈·Wi-Fi 끊김 등). + /// + /// 응답 본문이 없어 `network(_:_:)` 로 만들 수 없고, 그대로 두면 Moya 가 감싼 원문이 + /// 화면에 나간다 — 실제로 분석 실패 화면에 이렇게 떴다: + /// "URLSessionTask failed with error: The Internet connection appears to be offline." + case offline public static func == (lhs: APIError, rhs: APIError) -> Bool { switch (lhs, rhs) { case (.unknown, .unknown): return true case (.tokenReissuanceFailed, .tokenReissuanceFailed): return true + case (.offline, .offline): return true case (.network(let ls, _), .network(let rs, _)): return ls == rs default: return false } @@ -60,6 +67,9 @@ extension APIError: LocalizedError { return Self.message(statusCode: statusCode, code: problem.code) case .tokenReissuanceFailed: return "로그인이 만료됐어요. 다시 로그인해 주세요." + case .offline: + // 사용자가 실제로 할 수 있는 일을 말한다 — 서버 상태와 무관하게 기기 쪽 문제다. + return "인터넷 연결을 확인해 주세요." case .unknown: return Self.generic } diff --git a/Projects/Modules/Networks/Sources/Foundation/BaseService.swift b/Projects/Modules/Networks/Sources/Foundation/BaseService.swift index cc44159d..9d12bccd 100644 --- a/Projects/Modules/Networks/Sources/Foundation/BaseService.swift +++ b/Projects/Modules/Networks/Sources/Foundation/BaseService.swift @@ -226,6 +226,13 @@ extension BaseService { return apiError } + // 서버에 닿지도 못한 경우. 응답이 없어 아래 분기를 못 타고 원문이 그대로 화면에 나간다 + // ("URLSessionTask failed with error: The Internet connection appears to be offline."). + // Moya → AFError → URLError 로 감싸여 오므로 체인을 풀어 확인한다. + if let urlError = Self.urlError(in: error), Self.isOffline(urlError) { + return APIError.offline + } + guard let moya = error as? MoyaError, let response = moya.response, var problem = try? JSONDecoder().decode(NetworkError.self, from: response.data) else { @@ -235,4 +242,29 @@ extension BaseService { problem.rawBody = response.data return APIError.network(statusCode: response.statusCode, error: problem) } + + /// 감싸인 `URLError` 를 꺼낸다. Moya(underlying) → AFError(underlyingError) → URLError 순으로 중첩된다. + private static func urlError(in error: Error) -> URLError? { + if let urlError = error as? URLError { return urlError } + if case MoyaError.underlying(let underlying, _) = error { return urlError(in: underlying) } + if let afError = error as? AFError, let underlying = afError.underlyingError { + return urlError(in: underlying) + } + return nil + } + + /// "요청이 서버에 닿지 못했다" 로 볼 코드들. + /// + /// 타임아웃은 넣지 않는다 — 연결은 됐는데 서버·회선이 느린 경우라 "인터넷 연결을 확인하라"가 + /// 맞는 안내가 아니다. 일반 문구로 떨어뜨린다. + private static func isOffline(_ error: URLError) -> Bool { + switch error.code { + case .notConnectedToInternet, .networkConnectionLost, + .cannotConnectToHost, .cannotFindHost, + .dataNotAllowed, .internationalRoamingOff: + return true + default: + return false + } + } } diff --git a/Projects/Modules/Networks/Tests/Sources/OfflineErrorTests.swift b/Projects/Modules/Networks/Tests/Sources/OfflineErrorTests.swift new file mode 100644 index 00000000..94adb006 --- /dev/null +++ b/Projects/Modules/Networks/Tests/Sources/OfflineErrorTests.swift @@ -0,0 +1,65 @@ +import XCTest + +import Alamofire +import Moya + +@testable import Networks + +/// 서버에 닿지 못한 요청의 문구. +/// +/// 예전엔 Moya 가 감싼 원문이 그대로 화면에 나갔다 — 분석 실패 화면에 실제로 이렇게 떴다: +/// "URLSessionTask failed with error: The Internet connection appears to be offline." +/// 한국어 앱에 영문 기술 문장이 노출되므로 `APIError.offline` 로 좁혀 사용자 문구를 붙인다. +final class OfflineErrorTests: XCTestCase { + + /// 실제로 오는 형태 — Moya(underlying) → AFError(sessionTaskFailed) → URLError. + private func moyaOffline(_ code: URLError.Code) -> Error { + let urlError = URLError(code) + let afError = AFError.sessionTaskFailed(error: urlError) + return MoyaError.underlying(afError, nil) + } + + func test_연결없음은_offline로_해석된다() { + let interpreted = BaseService.interpret(moyaOffline(.notConnectedToInternet)) + + XCTAssertEqual(interpreted as? APIError, .offline) + XCTAssertEqual(interpreted.localizedDescription, "인터넷 연결을 확인해 주세요.") + } + + /// 기내모드·Wi-Fi 끊김·셀룰러 차단 등 "닿지 못함" 계열은 모두 같은 안내로 모은다. + func test_연결계열_코드들이_모두_offline() { + let codes: [URLError.Code] = [ + .notConnectedToInternet, .networkConnectionLost, + .cannotConnectToHost, .cannotFindHost, + .dataNotAllowed, .internationalRoamingOff, + ] + + for code in codes { + XCTAssertEqual( + BaseService.interpret(moyaOffline(code)) as? APIError, .offline, + "\(code) 는 서버에 닿지 못한 경우다" + ) + } + } + + /// 타임아웃은 연결은 됐는데 느린 것이라 "인터넷 연결을 확인하라"가 맞는 안내가 아니다. + /// 원문을 그대로 두어 기존 경로(일반 문구)로 떨어뜨린다. + func test_타임아웃은_offline이_아니다() { + XCTAssertNotEqual( + BaseService.interpret(moyaOffline(.timedOut)) as? APIError, .offline + ) + } +} + +// MARK: - Fixtures + +/// `interpret` 은 static 이라 Target 이 실제로 쓰이지 않는다 — 제네릭을 채우기 위한 최소 구현. +private enum TestAPI: TargetType { + case ping + + var baseURL: URL { URL(string: "https://example.com")! } + var path: String { "/ping" } + var method: Moya.Method { .get } + var task: Task { .requestPlain } + var headers: [String: String]? { nil } +}