简体   繁体   English

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

[英]Swift 4 with Firebase database OR Firestore read/write

I am fairly new at iOS development and very new with database integration.我在 iOS 开发方面相当新,并且对数据库集成非常陌生。 In short, I am trying to create a water tracker.简而言之,我正在尝试创建一个水跟踪器。 In both the Realtime Database AND Firestore, I can write new data and update data.在实时数据库和 Firestore 中,我都可以写入新数据和更新数据。 When I close and reopen the application, the console prints the current stored value.当我关闭并重新打开应用程序时,控制台会打印当前存储的值。 I am struggling with pulling that value into a label.我正在努力将该值拉入标签中。 My dictionary is setup (for example) ["Cups of Water:" x], I would like to put the value of x into the label but I can't seem to pull that value in.我的字典已设置(例如)["Cups of Water:" x],我想将 x 的值放入标签中,但我似乎无法提取该值。

The other issue I cannot seem to overcome is appending what the database has stored, instead of a complete overwrite.我似乎无法克服的另一个问题是附加数据库存储的内容,而不是完全覆盖。 When I close/reopen the application, the console prints "15" (for example), excluding my issue with being able to import the value into the label, if I touch an add cup button, it will overwrite the value of "15" and now display "1".当我关闭/重新打开应用程序时,控制台打印“15”(例如),排除我能够将值导入标签的问题,如果我触摸添加杯按钮,它将覆盖“15”的值现在显示“1”。

This is clearly something that I am not adding correctly and I have some ideas where the issue lies but I can't quite see it.这显然是我没有正确添加的内容,我对问题所在有一些想法,但我不太清楚。 Any input is greatly appreciated!非常感谢任何输入!

The code below is specific to the Firestore.下面的代码特定于 Firestore。 I can get a similar process working in the Realtime Database (by using the correct syntax).我可以在实时数据库中获得类似的过程(通过使用正确的语法)。 Code:代码:

@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()))")
            }
        }

First you have to match the key exactly so I think you should try this:首先,您必须完全匹配密钥,因此我认为您应该尝试以下操作:

myData["Cups Of Water"] 

instead of代替

myData["Cups of Water:"]

use this to safely unwrap the value from an optional:使用它来安全地从可选中解开值:

if let cupsOfWater = myData["Cups Of Water"] as? String { 

          self.totalWaterLabel.text = cupsOfWater 

}

this is called optional binding syntax , you can learn more here这称为optional binding语法,您可以在此处了解更多信息

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM