SwiftUI Firestore 기다려를 위한 데이터를 로드

0

질문

나는 데 문제가 검색 Firestore getdocument 데이터 앞에 보이 로드됩니다. 나는 그것에서 값을 반환 여러 검사 및 아마 문제로 어떻게 비동기 처리 기능입니다.

내 세 가지 변수를 설정합니다.

@Published var numParticipants = 0
@Published var totalAnswered = 0
@Published var showResults = false

이것은 첫 번째는 기능을 가져오고 설정 참가자의 수는 변수입니다.

func getRoom(roomId: String, onSuccess: @escaping(_ room: Room) -> Void) {
    DB.collection("Rooms").document(roomId).addSnapshotListener { document, error in
        DispatchQueue.main.async {
            if let dict = document?.data() {
                guard let decodeRoom = try? Room.init(fromDictionary: dict) else { return }
                onSuccess(decodeRoom)
            }
        }
    }
}

이 두 기능을 가져오고 설정하는 총 대답한 변수

func getNumParticipants(roomId: String, onSuccess: @escaping(_ numParticipants: Int) -> Void) {

    DB.collection("RoomsParticipants").document(roomId).collection("Participants").getDocuments { snapshot, error in
        DispatchQueue.main.async {
            if let error = error {
                print(error.localizedDescription)
                return
            } else {
                onSuccess(snapshot!.count)
            }
        }
    }
}

그리고 나서 이 마지막 기능 두 변수를 비교하고 로드 뷰 동일한 경우,그렇지 않으면 그냥 기다려야 할 때까지 그들이 동일합니다.

func checkShowResults(roomId: String) {
    isLoading = true
    
    self.getNumParticipants(roomId: roomId) { numParticipants in
        print("Number of docs: \(numParticipants)")
        DispatchQueue.main.async {
            self.numParticipants = numParticipants
        }
    }
    
    self.getRoom(roomId: roomId) { room in
        print("Total answered: \(room.totalAnswered)")
        DispatchQueue.main.async {
            self.totalAnswered = room.totalAnswered
            if self.totalAnswered == self.numParticipants {
                self.showResults = true
            }
        }
    }
    
    isLoading = false
}

여기에서 결과 보기 나려고를 표시하는 기반으로 가져온 데이터입니다.

struct ResultsView: View {

@StateObject var resultsViewModel = ResultsViewModel()
var roomId: String

var body: some View {
    VStack {
        if !resultsViewModel.showResults {
                VStack {
                    ProgressView()
                    Text("Waiting for all participants \nto finish answering...")
                }
            } else {
                ShowResultsView()
                }
            }
        }
    }.navigationBarHidden(true)
    .onAppear {
        resultsViewModel.checkShowResults(roomId: roomId)
    }
}

는 경우에도 totalAnswered 및 numParticipants 같은 경우는 처음으로 표시 showResults 은 항상 false 로 설정됩니다. 하지만 데이터 변경이 그것은 결국 true 로 설정하면 그들은 동등 다시합니다. 내가 생각하기 때문이 API 를 호출을 중포 기지/firestore 은 시간과 변수를 설정되지 않았습니다 전에 보니다. 내가 정말 원하지 않을 사용하여 비동기/이 기다리고 있습니다.

1

최고의 응답

2

현재 귀하의 코드를 실행 self.getNumParticipants(..) 독립적으로 self.getRoom(roomId: roomId). 그러나서 checkShowResults, self.getRoom(roomId: roomId)따라 달라집 에 self.numParticipants 에서 얻을 self.getNumParticipants(..). 그렇게 시도할 수 있습니다 중첩의 함수 호출합니다. 다음과 같은 코드:

func checkShowResults(roomId: String) {
    self.isLoading = true
    
    self.getNumParticipants(roomId: roomId) { numParticipants in
        print("Number of docs: \(numParticipants)")
        DispatchQueue.main.async {
            self.numParticipants = numParticipants
            
            // get the room after the numParticipants has been set
            self.getRoom(roomId: roomId) { room in
                print("Total answered: \(room.totalAnswered)")
                DispatchQueue.main.async {
                    self.totalAnswered = room.totalAnswered
                    if self.totalAnswered == self.numParticipants {
                        self.showResults = true
                        self.isLoading = false
                    }
                }
            }
            
        }
    }
2021-11-22 03:36:51

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................