Firebase在Swift中检索数据

Tim*_*Tim 7 ios firebase swift

我正在尝试从当前登录的用户中检索特定数据.我的数据库中的数据如下所示:

在此输入图像描述

例如,我想抓取full_name并将其保存在变量userName中.以下是我用来获取数据的方法

ref.queryOrderedByChild("full_name").queryEqualToValue("userIdentifier").observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
            print(snapshot.value)
            // let userName = snapshot.value["full_name"] as! String
        })
Run Code Online (Sandbox Code Playgroud)

不幸的是,这是我的控制台打印.

在此输入图像描述

我将不胜感激任何帮助:)谢谢!

Dog*_*fee 13

它会为您提供该警告消息,indexOn因为您正在进行查询.

您应该通过Security和Firebase规则中的.indexOn规则定义要编入索引的密钥.虽然您可以在客户端上临时创建这些查询,但在使用.indexOn时,您会看到性能大大提高

如您所知,您可以直接转到该节点,而无需查询.

    let ref:FIRDatabaseReference! // your ref ie. root.child("users").child("stephenwarren001@yahoo.com")

    // only need to fetch once so use single event

    ref.observeSingleEventOfType(.Value, withBlock: { snapshot in

        if !snapshot.exists() { return }

        //print(snapshot)

        if let userName = snapshot.value["full_name"] as? String {
            print(userName)
        }
        if let email = snapshot.value["email"] as? String {
            print(email)
        }

        // can also use
        // snapshot.childSnapshotForPath("full_name").value as! String
    })
Run Code Online (Sandbox Code Playgroud)


Kha*_*lam 5

斯威夫特4

let ref = Database.database().reference(withPath: "user")
    ref.observeSingleEvent(of: .value, with: { snapshot in

        if !snapshot.exists() { return }

        print(snapshot) // Its print all values including Snap (User)

        print(snapshot.value!)

        let username = snapshot.childSnapshot(forPath: "full_name").value
        print(username!)

    })
Run Code Online (Sandbox Code Playgroud)