Skip to content

Commit

Permalink
merge pull request #160
Browse files Browse the repository at this point in the history
�feat: 결과화면에서 로비로 이동, 결과화면 로딩 Alert 추가
  • Loading branch information
Sonny-Kor authored Dec 1, 2024
2 parents 07810f0 + e8dfce5 commit 97c6b8e
Show file tree
Hide file tree
Showing 10 changed files with 132 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public struct FirebaseEndpoint: Endpoint, Equatable {
case changeRecordOrder
case submitMusic
case submitAnswer
case resetGame

public var description: String {
switch self {
Expand All @@ -49,6 +50,8 @@ public struct FirebaseEndpoint: Endpoint, Equatable {
"/v2-submitAnswer"
case .changeRecordOrder:
"/changeRecordOrder"
case .resetGame:
"/resetGame"
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ public protocol MainRepositoryProtocol {
func disconnectRoom()

func postRecording(_ record: Data) async throws -> Bool
func postResetGame() async throws -> Bool
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public protocol RoomActionRepositoryProtocol {
func startGame(roomNumber: String) async throws -> Bool
func changeMode(roomNumber: String, mode: Mode) async throws -> Bool
func changeRecordOrder(roomNumber: String) async throws -> Bool
func resetGame() async throws -> Bool
}

public protocol MusicRepositoryProtocol {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,22 @@ public final class MainRepository: MainRepositoryProtocol {
guard let success = responseDict["success"] else { return false }
return success
}

public func postResetGame() async throws -> Bool {
let queryItems = [URLQueryItem(name: "userId", value: ASFirebaseAuth.myID),
URLQueryItem(name: "roomNumber", value: number.value)]
let endPoint = FirebaseEndpoint(path: .resetGame, method: .post)
.update(\.queryItems, with: queryItems)

let response = try await networkManager.sendRequest(
to: endPoint,
type: .none,
body: nil,
option: .none
)

let responseDict = try ASDecoder.decode([String: Bool].self, from: response)
guard let success = responseDict["success"] else { return false }
return success
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ public final class RoomActionRepository: RoomActionRepositoryProtocol {
return isSuccess
}

public func resetGame() async throws -> Bool {
return try await mainRepository.postResetGame()
}

private func sendRequest<T: Decodable>(endpointPath: FirebaseEndpoint.Path, requestBody: [String: Any]) async throws -> T {
let endpoint = FirebaseEndpoint(path: endpointPath, method: .post)
let body = try JSONSerialization.data(withJSONObject: requestBody, options: [])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,12 +366,14 @@ enum ASAlertText {
case startGame
case submitMusic
case submitHumming
case nextResult
var description: String {
switch self {
case .joinRoom: "방 정보를 가져오는 중..."
case .startGame: "게임을 시작하는 중..."
case .submitMusic: "노래를 전송하는 중..."
case .submitHumming: "허밍을 전송하는 중..."
case .nextResult: "다음 결과를 가져오는 중..."
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ final class ASButton: UIButton {

configurationUpdateHandler = { [weak self] _ in
guard let self else { return }
if self.isHighlighted {
self.transform = CGAffineTransform(scaleX: 0.96, y: 0.96)
if isHighlighted {
transform = CGAffineTransform(scaleX: 0.96, y: 0.96)
}
else {
self.transform = .identity
transform = .identity
}
}
configuration = config
Expand Down Expand Up @@ -91,7 +91,7 @@ final class ASButton: UIButton {
case .recording: setConfiguration(title: "녹음중..", backgroundColor: .asLightRed)
case .reRecord: setConfiguration(systemImageName: "arrow.clockwise", title: "재녹음", backgroundColor: .asOrange)
case .submit: setConfiguration(title: "제출하기", backgroundColor: .asGreen)
case .complete: setConfiguration(title: "완료")
case .complete: setConfiguration(title: "완료", backgroundColor: .asYellow)
case .submitted:
setConfiguration(title: "제출 완료")
disable()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,8 @@ class HummingResultViewController: UIViewController {
button.setConfiguration(systemImageName: "play.fill", title: "다음으로", backgroundColor: .asMint)
view.addSubview(button)
button.addAction(UIAction { [weak self] _ in
guard let self,
let viewModel else { return }
if !(viewModel.hummingResult.isEmpty) {
viewModel.changeRecordOrder()
}
else {
// let vc = self.navigationController?.viewControllers.first(where: { $0 is LobbyViewController })
// guard let vc else { return }
// self.navigationController?.popToViewController(vc, animated: true)
}
guard let self, let viewModel else { return }
showNextResultLoading()
}, for: .touchUpInside)
button.isHidden = true
}
Expand Down Expand Up @@ -122,13 +114,28 @@ class HummingResultViewController: UIViewController {
viewModel.nextResultFetch()
button.isHidden = true
if viewModel.hummingResult.isEmpty {
button.setConfiguration(title: "완료", backgroundColor: .asYellow)
button.updateButton(.complete)
}
viewModel.isNext = false
}
}
.store(in: &cancellables)
}

private func nextResultFetch() async throws {
guard let viewModel else { return }
do {
if viewModel.hummingResult.isEmpty {
try await viewModel.navigationToLobby()
}
else {
try await viewModel.changeRecordOrder()
}
}
catch {
throw error
}
}
}

extension HummingResultViewController: UITableViewDataSource {
Expand Down Expand Up @@ -242,6 +249,26 @@ extension HummingResultViewController: UITableViewDataSource {
}
}

extension HummingResultViewController {
private func showNextResultLoading() {
let alert = ASAlertController(
progressText: .nextResult,
load: { [weak self] in
try await self?.nextResultFetch()
},
errorCompletion: { [weak self] error in
self?.showFailNextLoading(error)
}
)
presentLoadingView(alert)
}

private func showFailNextLoading(_ error: Error) {
let alert = ASAlertController(titleText: .error(error))
presentAlert(alert)
}
}

final class MusicResultView: UIView {
private let albumImageView = UIImageView()
private let musicNameLabel = UILabel()
Expand Down Expand Up @@ -288,7 +315,7 @@ final class MusicResultView: UIView {
}

private func setupView() {
self.backgroundColor = .asSystem
backgroundColor = .asSystem

titleLabel.text = "정답은..."
titleLabel.font = .font(ofSize: 24)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import Foundation
import Combine
import ASRepositoryProtocol
import ASAudioKit
import ASEntity
import ASLogKit
import ASRepositoryProtocol
import Combine
import Foundation

final class HummingResultViewModel: @unchecked Sendable {
private var hummingResultRepository: HummingResultRepositoryProtocol
Expand Down Expand Up @@ -35,7 +35,8 @@ final class HummingResultViewModel: @unchecked Sendable {
playerRepository: PlayersRepositoryProtocol,
roomActionRepository: RoomActionRepositoryProtocol,
roomInfoRepository: RoomInfoRepositoryProtocol,
musicRepository: MusicRepositoryProtocol) {
musicRepository: MusicRepositoryProtocol)
{
self.hummingResultRepository = hummingResultRepository
self.avatarRepository = avatarRepository
self.gameStatusRepository = gameStatusRepository
Expand All @@ -51,28 +52,28 @@ final class HummingResultViewModel: @unchecked Sendable {
hummingResultRepository.getResult()
.receive(on: DispatchQueue.main)
.sink { completion in
//TODO: 성공 실패 여부에 따른 처리
// TODO: 성공 실패 여부에 따른 처리
Logger.debug(completion)
} receiveValue: { [weak self] (result: [(answer: ASEntity.Answer, records: [ASEntity.Record], submit: ASEntity.Answer, recordOrder: UInt8)]) in
// 분명 받았던 데이터인데 계속 값이 들어옴
guard let self else { return }

if (result.count - 1) < result.first?.recordOrder ?? 0 { return }
Logger.debug("호출")
self.hummingResult = result.map {
return (answer: $0.answer, records: $0.records, submit: $0.submit)
hummingResult = result.map {
(answer: $0.answer, records: $0.records, submit: $0.submit)
}

self.hummingResult.sort {
hummingResult.sort {
$0.answer.player?.order ?? 0 < $1.answer.player?.order ?? 1
}

Logger.debug("hummingResult \(self.hummingResult)")
Logger.debug("hummingResult \(hummingResult)")

let current = self.hummingResult.removeFirst()
self.currentResult = current.answer
self.recordsResult = current.records
self.submitsResult = current.submit
let current = hummingResult.removeFirst()
currentResult = current.answer
recordsResult = current.records
submitsResult = current.submit
}
.store(in: &cancellables)

Expand All @@ -92,32 +93,31 @@ final class HummingResultViewModel: @unchecked Sendable {

Publishers.CombineLatest(gameStatusRepository.getStatus(), gameStatusRepository.getRecordOrder())
.receive(on: DispatchQueue.main)
.sink { status, order in
.sink { status, _ in
// order에 초기값이 들어오는 문제
if (status == .result && self.recordOrder != 0) {
if status == .result, self.recordOrder != 0 {
self.recordOrder! += 1
self.isNext = true
}
else {
} else {
self.recordOrder! += 1
}
}
.store(in: &cancellables)
}

func startPlaying() async -> Void {
while !recordsResult.isEmpty {
currentRecords.append(recordsResult.removeFirst())
guard let fileUrl = currentRecords.last?.fileUrl else { continue }
do {
let data = try await fetchRecordData(url: fileUrl)
await AudioHelper.shared.startPlaying(data)
await waitForPlaybackToFinish()
} catch {
Logger.error("녹음 파일 다운로드에 실패하였습니다.")
}
func startPlaying() async {
while !recordsResult.isEmpty {
currentRecords.append(recordsResult.removeFirst())
guard let fileUrl = currentRecords.last?.fileUrl else { continue }
do {
let data = try await fetchRecordData(url: fileUrl)
await AudioHelper.shared.startPlaying(data)
await waitForPlaybackToFinish()
} catch {
Logger.error("녹음 파일 다운로드에 실패하였습니다.")
}
currentsubmit = submitsResult
}
currentsubmit = submitsResult
}

private func waitForPlaybackToFinish() async {
Expand All @@ -133,21 +133,21 @@ final class HummingResultViewModel: @unchecked Sendable {
}

func nextResultFetch() {
if self.hummingResult.isEmpty { return }
let current = self.hummingResult.removeFirst()
self.currentResult = current.answer
self.recordsResult = current.records
self.submitsResult = current.submit
self.currentRecords.removeAll()
self.currentsubmit = nil
if hummingResult.isEmpty { return }
let current = hummingResult.removeFirst()
currentResult = current.answer
recordsResult = current.records
submitsResult = current.submit
currentRecords.removeAll()
currentsubmit = nil
}

private func getRecordData(url: URL?) -> AnyPublisher<Data?, Error> {
if let url {
return hummingResultRepository.getRecordData(url: url)
hummingResultRepository.getRecordData(url: url)
.eraseToAnyPublisher()
}else {
return Just(nil)
} else {
Just(nil)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
Expand All @@ -173,13 +173,21 @@ final class HummingResultViewModel: @unchecked Sendable {
return await avatarRepository.getAvatarData(url: url)
}

func changeRecordOrder() {
Task {
do {
try await self.roomActionRepository.changeRecordOrder(roomNumber: roomNumber)
} catch {
Logger.error(error.localizedDescription)
}
func changeRecordOrder() async throws {
do {
try await roomActionRepository.changeRecordOrder(roomNumber: roomNumber)
} catch {
Logger.error(error.localizedDescription)
throw error
}
}

public func navigationToLobby() async throws {
do {
if !hummingResult.isEmpty { return }
try await roomActionRepository.resetGame()
} catch {
throw error
}
}

Expand Down
Loading

0 comments on commit 97c6b8e

Please sign in to comment.