Search code examples
swiftswift-concurrency

Swiftui async / await with Firebase


I am trying to get the last AppVersion dokument out from the database!

What am I doing wrong here?

func getLastAppVertion() async throws -> ApplicationVersion {
            firebase.collection("ApplicationVersion")
                    .order(by: "major")
                    .order(by: "minor")
                    .order(by: "patch")
                    .limit(to: 1)
                    .getDocuments { (querySnapshot, error) in
                        if let error = error {
                            throw AppError.networkerror
                        } else {
                            for document in querySnapshot!.documents {
                                let major = document.data()["major"] as? Int ?? 7
                                let minor = document.data()["minor"] as? Int ?? 15
                                let patch = document.data()["patch"] as? Int ?? 0
                                let sendAppVersion = ApplicationVersion(major: major,
                                                                        minor: minor,
                                                                        patch: patch,
                                                                        device: .iPhone)
                                return sendAppVersion
                        }
                    }
                }
    }

Solution

  • You are calling getDocuments with a completion handler.

    You cannot mix Swift structured concurrency async/await directly with getDocuments / completion handler. async/await and completion handler are opposites.

    Everything about your completion handler is wrong. You cannot throw from a completion handler. You cannot return anything from a completion handler. That's the whole point of async/await. That is why async/await supersedes completion handlers.

    To wrap async/await around a completion handler call, you must use withUnsafeThrowingContinuation.