访问Firebase数据库中的多个节点

如何解决访问Firebase数据库中的多个节点

我很难从Firebase数据库中的一个节点中提取所有数据。

以下是该节点在Firebase中的外观:

Considerations
     -MEdUNZwVrsDW3dTrE6N
        Company Description: 
        Company Image: 
        Company Name: 
        Decision Date: 
        Start Date: 
        Users
           B2Z4DlZ8RucvEQhz2NSUkquqc5P2
              Compensation: 
              PostNumber: 
              StoryNumber:

在用户下,将会有多个人的补偿,职位号和故事号具有不同的值。我让每个用户都有一个名为“用户注意事项”的节点,该节点标记每个用户附加的注意事项的唯一ID,并将其放在其UID下,并将其旁边的1标记为值。我正在尝试访问每个特定用户的信息以及节点中的其他信息。这是我用来调用信息的代码以及用来捕获信息的结构:

结构:

import UIKit

class ConsiderationInfo: NSObject {
    var companyName: String?
    var companyImage: String?
    var companyDescription: String?
    var decisionDate: String?
    var startDate: String?
    var compensation: String?
    var postNumber: String?
    var storyNumber: String?
}

用于查看信息的代码:

 func updateConsiderationsArray() {
    
    let uid = Auth.auth().currentUser?.uid
    let ref = Database.database().reference().child("user-considerations").child(uid!)
            
            ref.observe(.childAdded,with: { (snapshot) in
            
                    let considerationId = snapshot.key
                    let considerationReference = Database.database().reference().child("Considerations").child(considerationId)
            
                    considerationReference.observe(.value,with: { (snapshot) in

                    if let dictionary = snapshot.value as? [String: AnyObject] {
                    let considerationInfo = ConsiderationInfo()
                    //self.setValuesForKeys(dictionary)
                    considerationInfo.companyName = dictionary["Company Name"] as? String
                    considerationInfo.companyImage = dictionary["Company Image"] as? String
                    considerationInfo.companyDescription = dictionary["Company Description"] as? String
                    considerationInfo.decisionDate = dictionary["Decision Date"] as? String
                    considerationInfo.startDate = dictionary["Start Date"] as? String
                
                    self.considerationsInfo.append(considerationInfo)
                    self.considerationName.append(considerationInfo.companyName!)
                    self.filteredConsiderations.append(considerationInfo.companyName!)
                        
                        self.considerationCollectionView.reloadData()
                }
            },withCancel: nil)
        })
    }

我正在尝试访问用户特定节点下的信息,即特定用户的补偿职位编号和故事编号。我不知道如何访问所有这些内容以附加该结构。

这是具有用户注意事项的节点:

user node

解决方法

就目前而言,我确实没有看到任何超级错误的代码,但是有几件事可以更改以使其更加简化。

我将首先更改“注意事项”类以使其更加独立。添加便捷初始化程序以通过一些错误检查直接处理Firebase快照。

class ConsiderationInfo: NSObject {
    var companyName = ""

    convenience init(withSnapshot: DataSnapshot) {
        self.init()
        self.companyName = withSnapshot.childSnapshot(forPath: "Company Name").value as? String ?? "No Company Name"
    }
}

我还建议删除.childAdded和.observe事件,除非您特别希望将来发生更改时收到通知。请改用.value和.observeSingleEvent。请记住,.childAdded一次遍历数据库中的每个节点-.value一次读取所有节点。如果数据量有限,.value效果很好。

    func updateConsiderationsArray() {
        let fbRef = Database.database().reference()
        let uid = Auth.auth().currentUser?.uid
        let ref = fbRef.child("user_considerations").child(uid)
        ref.observeSingleEvent(of: .value,with: { snapshot in
            let allUidsSnap = snapshot.children.allObjects as! [DataSnapshot]
            for uidSnap in allUidsSnap {
                let considerationId = uidSnap.key
                let considerationReference = fbRef.child("Considerations").child(considerationId)
                considerationReference.observeSingleEvent(of: .value,with: { snapshot in
                    let considerationInfo = ConsiderationInfo(withSnapshot: snapshot)
                    self.considerationArray.append(considerationInfo)
                    // update your collectionView
                })
            }
        })
    }

我在上面所做的是从user_considerations中读取单个节点,根据您的要求,它看起来像这样

user_considerations
   some_user_uid
      a_user_uid
      a_user_uid

然后将每个子用户映射到一个数组以维持顺序

let allUidsSnap = snapshot.children.allObjects as! [DataSnapshot]

,然后遍历每个节点,获取每个节点的uid(键),然后从“注意事项”节点获取该节点的数据。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-