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

时间:2019-04-05 07:51:44

标签: ios swift firebase google-cloud-firestore

我正在尝试从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")
    }
}

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

1 个答案:

答案 0 :(得分:0)

我建议您查看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文档中所述。