Swift 4 个,使用 Firebase 数据库或 Firestore read/write

Swift 4 with Firebase database OR Firestore read/write

我在 iOS 开发方面还很陌生,对数据库集成也很陌生。简而言之,我正在尝试创建一个水跟踪器。在实时数据库和 Firestore 中,我都可以写入新数据和更新数据。当我关闭并重新打开应用程序时,控制台会打印当前存储的值。我正在努力将这种价值融入标签中。我的字典已设置(例如)["Cups of Water:" x],我想将 x 的值放入标签中,但我似乎无法将该值拉入。

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

这显然是我没有正确添加的东西,我对问题所在有一些想法,但我不太明白。非常感谢任何输入!

以下代码特定于 Firestore。我可以在实时数据库中获得类似的过程(通过使用正确的语法)。 代码:

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

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

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