带Firebase数据库的Swift 4或Firestore读/写

时间:2017-10-07 14:38:55

标签: ios swift firebase google-cloud-firestore

我在iOS开发方面相当新,而且在数据库集成方面非常新。简而言之,我正在努力创建一个水跟踪器。在实时数据库和Firestore中,我可以编写新数据和更新数据。当我关闭并重新打开应用程序时,控制台会打印当前存储的值。我正在努力将这个价值拉入标签。我的字典是设置的(例如)["水杯:" x],我想将x的值放入标签中,但我似乎无法提取该值。

我似乎无法克服的另一个问题是追加数据库存储的内容,而不是完全覆盖。当我关闭/重新打开应用程序时,控制台会打印" 15" (例如),除了我能够将值导入标签的问题,如果我触摸添加杯按钮,它将覆盖" 15"现在显示" 1"。

这显然是我没有正确添加的东西,我有一些想法,但我无法看到它。任何输入都非常感谢!

以下代码特定于Firestore。我可以在Realtime Database中使用类似的进程(使用正确的语法)。 代码:

@IBOutlet weak var totalWaterLabel: UILabel!

var ref: DocumentReference? = nil
var variableCupsOfWater = 0
var handle: AuthStateDidChangeListenerHandle?
var waterListener: FIRListenerRegistration!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func addOnePressed(_ sender: UIButton) {
    variableCupsOfWater += 1
    totalWaterLabel.text = String(variableCupsOfWater)
    saveToFirestore()
}
@IBAction func addTwoPressed(_ sender: Any) {
    variableCupsOfWater += 2
    totalWaterLabel.text = String(variableCupsOfWater)
    saveToFirestore()
}
@IBAction func addFourPressed(_ sender: UIButton) {
    variableCupsOfWater += 4
    totalWaterLabel.text = String(variableCupsOfWater)
    saveToFirestore()
}

func saveToFirestore() {
    let _: DocumentReference? = nil
    let db = Firestore.firestore()
    let user = Auth.auth().currentUser
    let uid = user!.uid

    db.collection("By User").document("\(uid)").updateData([
        "Cups Of Water": "\(totalWaterLabel.text!)",
        "Date": NSDate()
    ]) { err in
        if let err = err {
            print("Error adding document: \(err)")
        } else {
            print("Document added")
        }
    }
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
        print(Auth.auth().currentUser as Any)
    })
    let db = Firestore.firestore()
    let user = Auth.auth().currentUser
    let uid = user!.uid


    db.collection("By User").document("\(uid)")
        .addSnapshotListener { querySnapshot, error in
                    guard let querySnapshot = querySnapshot, querySnapshot.exists else {return}
            let myData = querySnapshot.data()
            let currentWaterTotal = myData["Cups of Water:"] as? String ?? ""
            let combinedCups = ("\(currentWaterTotal)") + self.totalWaterLabel.text!
            self.totalWaterLabel.text = "\(querySnapshot.data())"
            if let error = error {
                print("Error retreiving collection: \(error)")
            }else{

                print("Current data: \(String(describing: querySnapshot.data()))")
            }
        }

1 个答案:

答案 0 :(得分:1)

首先你必须完全匹配密钥,所以我认为你应该试试这个:

myData["Cups Of Water"] 

而不是

myData["Cups of Water:"]

使用它来安全地从可选的

中解包值
if let cupsOfWater = myData["Cups Of Water"] as? String { 

          self.totalWaterLabel.text = cupsOfWater 

}

这称为optional binding语法,您可以在这里了解更多

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html