gpt4 book ai didi

ios - 如何存储(在变量中)从 Xcode 中的数据库读取的 Firestore 文档数据

转载 作者:行者123 更新时间:2023-11-29 05:52:44 24 4
gpt4 key购买 nike

我正在尝试从 Firebase Firestore 读取数据,但无法将文档数据存储在变量中,因为这些变量只是本地变量,并且会被“垃圾收集”

我尝试创建一个尝试返回文档内容的函数,但这导致了错误,因为“getDocument”方法不允许返回类型。

docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
var dataValues = document.data()!.values
self.textInput = dataDescription
//I first tried doing it without the word self, but it gave an error insisting that I add self, but adding it makes it a local variable and not the String variable defined in the class
//textInput is a String
print("Document data: \(document.data()!.values)")
//This will print out everything in the document
} else {
print("Document does not exist")
}
}

我试图看看是否可以为文档数据设置任何变量,并且在读取数据库后仍然能够访问数据。

最佳答案

我建议您查看https://firebase.google.com/docs/firestore/manage-data/transactions ,Firebase 有最完整的文档之一,这会对您有所帮助,确切地说您应该这样做:

let sfReference = db.collection("cities").document("SF")

db.runTransaction({ (transaction, errorPointer) -> Any? in
let sfDocument: DocumentSnapshot
do {
try sfDocument = transaction.getDocument(sfReference)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}

guard let oldPopulation = sfDocument.data()?["population"] as? Int else {
let error = NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
]
)
errorPointer?.pointee = error
return nil
}

// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference)
return nil
}) { (object, error) in
if let error = error {
print("Transaction failed: \(error)")
} else {
print("Transaction successfully committed!")
}
}

如 Firebase 文档中所述。

关于ios - 如何存储(在变量中)从 Xcode 中的数据库读取的 Firestore 文档数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55530653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com