Swiftui async / await with Firebase



我正试图从数据库中获得最后的AppVersion文档!

我在这里做错了什么?

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
}
}
}
}

您将旧的异步调用与新的并发性混合在一起。

你需要用withUnsafeThrowingContinuation来转换它,就像这样:

func getLastAppVertion() async throws -> Float {
try withUnsafeThrowingContinuation { continuation in
firebase.collection("ApplicationVersion")
.order(by: "major")
.order(by: "minor")
.order(by: "patch")
.limit(to: 1)
.getDocuments { (querySnapshot, error) in
if let error = error {
continuation.resume(throwing: AppError.networkerror)
return
} 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)
continuation.resume(returning: 1)
// not sure why you're using a for loop and returning the first value here
return
}
}
}
}
}

我建议你从Swift并发开始:更新一个示例应用程序和其他WWDC关于Swift并发的演讲,以了解如何使用它。

您正在使用一个完成处理程序调用getDocuments

你不能将Swift结构化并发async/await直接与getDocuments/完成处理程序混合。async/await和完成处理程序是相反的。

关于你的完成处理程序的一切都是错误的。不能从完成处理程序抛出。你不能从一个完成处理程序返回任何东西。这就是async/await的全部意义。这就是为什么async/await取代了完成处理程序。

要将async/await封装在完成处理程序调用之外,必须使用withUnsafeThrowingContinuation

最新更新