尝试使用Swift 3从Firebase检索数据时出现问题

时间:2017-02-20 12:18:50

标签: ios swift xcode firebase firebase-realtime-database

我正在尝试从Firebase数据库中检索数据。我使用JSON来获取数据。使用SwiftyJSON库。

这是我的代码:

func retrieveUserDatabaseAdress(userID: String) {

    let userRef = ref.child("users").child(userID)

    UIApplication.shared.isNetworkActivityIndicatorVisible = true
    userRef.observeSingleEvent(of: .value, with: { snapshot in

        let json = JSON(snapshot)
        print("test")
        self.address = json["address"].stringValue
        UIApplication.shared.isNetworkActivityIndicatorVisible = false

    }) { error in
        print(error.localizedDescription)
    }
}

这是我的数据库层次结构

-users  
---S4KaKn5Qz4bDDha57DMLcnaCHn22
-------address: ...
-------email: ...
-------name: ...
-------tel: ...

问题:它始终检索零值。另外,打印("测试")不会被执行。

我检查了用户是否已登录以获取读取规则:它没问题。 我也试过其他方法,不工作。 我的Firebase数据库似乎配置正确,因为我可以写数据......但无法读取数据......

2 个答案:

答案 0 :(得分:0)

这应该有效:

userRef.observeSingleEvent(of: .value, with:  { (snapshot) in
    if let value = snapshot.value as? [String: AnyObject] {
        let json = JSON(value)
        print(json)
    } else {
        // No value
    }
}, withCancel: { (error) in
    print(error)
})

答案 1 :(得分:0)

首先将数据库的根路径作为“用户”传递。
此代码在我的数据库中正常工作。它可能适用于您的情况。你应该尝试:)

let childRef = FIRDatabase.database().reference(withPath: "users")

        childRef.observe(.value, with: { snapshot in

            for item in snapshot.children {

                 let json = JSON(item)
                print(json)

            }

        })
相关问题