1

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

我似乎无法克服的另一个问题是附加数据库存储的内容,而不是完全覆盖。当我关闭/重新打开应用程序时,控制台会打印“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()))")
            }
        }
4

1 回答 1

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

于 2017-10-08T14:44:43.927 回答