ios - 为什么它会覆盖数据而不是在 firebase 中添加更多数据?

标签 ios swift firebase firebase-realtime-database

我很想知道为什么当用户输入新数据时数据会被覆盖, 我希望它向它添加更多数据而不是覆盖它的数据 也想知道怎么读 提前谢谢你

 let oDB = Database.database().reference().child("Data")
    let oDictionary = ["Data1" : strange.text! , "Data2" : stranger.text!]
    let uid = Auth.auth().currentUser?.uid
    oDB.child(uid!).setValue(oDictionary) {

        (error, reference) in
        if error != nil{
            print(error!)
        } else  {
            print("saved Sucessfully")
            self.navigationController?.popViewController(animated: true)

        }
    }

 //In another ViewController
 func updateRequest() {
    let uid = Auth.auth().currentUser?.uid
    let yDb = Database.database().reference().child("Data").child(uid!)
    postDb.observeSingleEvent(of: .value) { (snapShot) in
        if let snapShotValue = snapShot.value as? Dictionary<String, String> {

        let text = snapShotValue["Data1"]!
        let case = snapShotValue["Data2"]!


        let data = Data()
        data.s= text
        data.y = case

        self.array.append(data)
        self.table.reloadData()
    }
    }
}

最佳答案

setValue 覆盖旧内容,你可能需要childByAutoId

oDB.child(uid!).childByAutoId().setValue(oDictionary) {

    (error, reference) in
    if error != nil{
        print(error!)
    } else  {
        print("saved Sucessfully")
        self.navigationController?.popViewController(animated: true)

    }

这将给出这个结构

Data 
  > uid
    > someKey1             <<<< auto generated 
        Data1:"---"
        Data2:"---"
    > someKey2             <<<< auto generated 
        Data1:"---"
        Data2:"---"

阅读

 //In another ViewController
 func updateRequest() {
    let uid = Auth.auth().currentUser?.uid
    let yDb = Database.database().reference().child("Data").child(uid!)
    postDb.observeSingleEvent(of: .value) { (snapShot) in
        if let snapShotValue = snapShot.value as? [String:[String:String]] {

          Array(snapShotValue.values).forEach {
            let data = Data()
            data.s= $0["Data1"]!
            data.y = $0["Data2"]! 
            self.array.append(data)
         }

        self.table.reloadData()
    }
    }
}

关于ios - 为什么它会覆盖数据而不是在 firebase 中添加更多数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57169955/

相关文章:

swift - 错误: "Type ' any' has no subscript members"in my Swift 3 project when I am retrieving info from Firebase

android - FirebaseCloudMessaging : FirebaseInstanceId background sync failed - SERVICE_NOT_AVAILABLE

ios - Swift:将 SKshapeNode 定位到最左/最右但不在屏幕外

ios - 如何在 Xcode 中查看 View Controller 的代码 View ?

ios - 在 AFNetworking 运行时更改 SSL 固定模式

swift - 自定义操作按钮未显示用于远程通知

javascript - 如何在我的 phonegap 应用程序中从网页导航到本地页面?

ios - Firebase 遍历嵌套数据并存储在数组中

ios - 如何向 Storyboard快速创建的 UIBarButtonItem 添加 Action ?

android - react-native-firebase crashlytics 未显示在 firebase 仪表板上