检索嵌套密钥Firebase数据库

时间:2017-01-02 15:49:42

标签: ios swift firebase firebase-realtime-database

我在Swift中开发了一个使用Firebase作为后端的应用程序。

void GetRemoteList ()
{
    string fileListBuffer = "";
    curl_easy_setopt(m_curl, CURLOPT_URL, sRemoteURL.c_str());  // Target URL
    curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, &getRemoteListCallback );
    curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, &fileListBuffer );  

    curl_easy_setopt(m_curl, CURLOPT_VERBOSE, 1);
    curl_easy_setopt(m_curl, CURLOPT_DIRLISTONLY, 1L);
    curl_easy_setopt(m_curl, CURLOPT_USERPWD,   sUserPassword.c_str());
    curl_easy_setopt(m_curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);

    CURLcode res = curl_easy_perform(m_curl);

....

}

我想检索用户名并用消息显示,我试试这段代码:

MESSAGES
   -KW83KXYFzNgo-ibxKQV
        --dateSent: "2016-09-09 12:30:23+0000"
        --smiley:"smiley1"
        --userID:"0QggCGYr46fcz3ak8tcQjsyZ9sJ2"
Users 
  -- 0QggCGYr46fcz3ak8tcQjsyZ9sJ2
      --name: "john"
      --photo:"photoURL"

结果如下:

self.ref = FIRDatabase.database().reference()
self.ref.child("messages").observe(.childAdded, with: { snapshot in        
   if let snapshotValue = snapshot.childSnapshot(forPath: Constants.Messages.senderId).value {
     FIRDatabase.database().reference().child("Users")
         .child(snapshotValue as! String).observe(.value, with: {userSnapshot in
            if let userSnapshotValue = userSnapshot.value as? [String:Any] {
                self.usernames.append(userSnapshotValue[Constants.UserFields.nickName] as! String)
            }
        })

因此代码检索密钥,但没有执行嵌套查询。任何命题?

1 个答案:

答案 0 :(得分:0)

这是您想要的简化且更详细的版本:

    let usersRef = ref.child("users")
    let postsRef = ref.child("posts")

    postsRef.observe(.childAdded, with: { (postSnap) in

        let postDict = postSnap.value as! [String:AnyObject]
        let msg = postDict["msg"]!
        let userId = postDict["user_id"] as! String

        let thisUserRef = usersRef.child(userId)
        thisUserRef.observeSingleEvent(of: .value, with: { userSnap in

            let userDict = userSnap.value as! [String: AnyObject]
            let userName = userDict["name"] as! String
            print("msg: \(msg)")
            print("  fromUid: \(userId)")
            print("  userName: \(userName)")
        })
    })

和输出

msg: some message from uid_0
  fromUid: uid_0
  userName: Bill
msg: some message from uid_1
  fromUid: uid_1
  userName: Leroy

和Firebase结构

users
  uid_0
    name: "Bill"
  uid_1
    name: "Leroy"
posts
  post_0
   msg: "some message from uid_0"
   user_id: "uid_0"
  post_1
   msg: "some message from uid_1"
   user_id: "uid_1"
相关问题