Swift 3和Firebase:从快照中检索自动ID值 [英] Swift 3 and Firebase: Retrieve auto id value from snapshot

查看:64
本文介绍了Swift 3和Firebase:从快照中检索自动ID值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在firebase上创建了以下结构,我需要用红色下划线标记自动编号:

I created the structure below on firebase and I need to get the auto id underlined in red:

我创建的用于查询值的代码:

The code I created to query the values:

let query = reference.queryOrdered(byChild: "receiverId").queryEqual(toValue: "LKupL7KYiedpr6uEizdCapezJ6i2")
        //Start process
        query.observe(.value, with: { (snapshot) in
            guard snapshot.exists() else{
                print("Data doesn't exists")
                return
            }
            print(snapshot.key)
}

我的" snapshot.value "的结果是:

Optional({
    "-KaRVjQgfFD00GXurK9m" =     {
        receiverId = LKupL7KYiedpr6uEizdCapezJ6i2;
        senderId = bS6JPkEDXIVrlYtSeQQgOjCNTii1;
        timestamp = 1484389589738;
    };
})

如何从上面的节点中仅获取字符串 -KaRVjQgfFD00GXurK9m ?

How do I get only the string -KaRVjQgfFD00GXurK9m from the node above?

我曾经尝试使用" print(snapshot.key)",但是它会导致用户ID出现: bS6JPkEDXIVrlYtSeQQgOjCNTii1

I had tried using "print(snapshot.key)" but it results on the user ID: bS6JPkEDXIVrlYtSeQQgOjCNTii1

有些想法?非常感谢.

推荐答案

.value返回满足查询结果的父节点和所有子节点.在这种情况下,需要对子项进行迭代(可能有超过1个与查询匹配的子项).

.value returns the parent node and all of the child nodes that satisfy the results of the query. In this case, the children would need to be iterated over (there could be more than 1 child that matches the query).

snapshot.key是父节点密钥(bS6JPkEDXIVrlYtSeQQgOjCNTii1),值是所有子代的快照(字典).这些子节点中的每个子节点都是uid:value的key:value对,并且value子节点的字典,receiverId,senderId等.

The snapshot.key is the parent node key (bS6JPkEDXIVrlYtSeQQgOjCNTii1) and the value is a snapshot (dictionary) of all of the children. Each of those children is a key:value pair of uid:value and value a dictionary of the child nodes, receiverId, senderId etc

此代码将为每个与查询匹配的用户节点打印每个子节点的uid和值timestamp.

This code will print the uid of each child node and one of the values, timestamp, for each user node that matches the query.

    let usersRef = ref.child("users")
    let queryRef = usersRef.queryOrdered(byChild: "receiverId")
                           .queryEqual(toValue: "LKupL7KYiedpr6uEizdCapezJ6i2")

    queryRef.observeSingleEvent(of: .value, with: { (snapshot) in

        for snap in snapshot.children {
            let userSnap = snap as! FIRDataSnapshot
            let uid = userSnap.key //the uid of each user
            let userDict = userSnap.value as! [String:AnyObject]
            let timestamp = userDict["timestamp"] as! String
            print("key = \(uid) and timestamp = \(timestamp)")
        } 
    })

这篇关于Swift 3和Firebase:从快照中检索自动ID值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆