ios - 从 Firebase 检索数据后对其进行操作

标签 ios swift firebase firebase-realtime-database

这是我的代码:

//从Firebase获取数据

    func getData(withBlock completion:@escaping() ->Void){
    let ref = Database.database().reference().child("hobbies")
    let query = ref.queryOrdered(byChild: "cost").queryEqual(toValue: "low")
    query.observe(.childAdded, with: {(snapshot) in
        self.user_choice_Cost.append((snapshot.childSnapshot(forPath: "hobbyName").value as? String)!)
        completion()
        //print(self.user_choice_Cost)
    })
    { (error) in
    print(error)
    }

//操作数据

    getData{
    let set2:Set<String> = ["a"]
    let set1:Set<String> = Set(self.user_choice_Cost)
    print(set1.union(set2))}

这可以正常工作!但是有什么方法可以让 user_choice_Cost 具有所有值([“a”,“b”])而不是一一([“a”],[“a”,“b”)]并操作 user_choice_Cost 数组而不将其放入 getData{} 内。因为如果我把它放在外面它只会返回“a”

最佳答案

当您观察 .childAdded 时,系统会为与您的查询匹配的每个子项调用您的完成处理程序。如果您只想为所有匹配的子项调用一次,您应该观察 .value:

    query.observe(.value, with: {(snapshot) in

由于您的完成处理程序仅被调用一次,因此本例中的快照包含所有匹配的节点。因此,您需要循环 snapshot.children:

    query.observe(.value, with: {(snapshot) in
        for child in snapshot.children.allObjects as! [DataSnapshot] {
            let value: String = (child.childSnapshot(forPath: "hobbyName").value as? String)!;
            user_choice_Cost.append(value)
        }
        print("value \(user_choice_Cost)")
    })

使用此代码,您只会看到一个日志输出,以及所有匹配的爱好名称。

关于ios - 从 Firebase 检索数据后对其进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46789388/

相关文章:

iphone - 给定一个异步 block ,如何知道该 block 何时完成?

ios5 - UITableViewCell 子类中的 IFTweetLabel 未显示

使用动态组件自定义 Angular URL(路由)

android - 无法在 ImageView 中显示来自 Firebase 存储的图像

ios - 发送http post请求时NSURLErrorDomain Code=-1001错误

ios - Facebook native 登录不会打开 facebook 应用程序,即使它已安装在设备中?

swift - 如何通过代码在 SceneKit 中设置基于物理的渲染?

ios - 我可以在 iOS 钥匙串(keychain)中为单个用户存储/检索多个密码吗?

ios - ECC Curve25519 钥匙串(keychain)

angular - 引用错误 : IDBIndex is not defined Angular SSR