使用结构文件从Firebase提取数据时出现问题

时间:2019-07-26 07:52:13

标签: swift firebase firebase-realtime-database

struct UserClass {
    var babyName: String!
    var babyHeight: String!
    var babyWeight: String!
    var babyURL: String!

    var uid: String!
    var reference:DatabaseReference!
    var key: String!

    init?(snapshot: DataSnapshot?) {
        guard let value = snapshot?.value as? [String:AnyObject],

            let uid = value["uid"] as? String,
            let babyName = value["BabyName"] as? String,
            let babyURL = value["BabyURL"] as? String,
            let babyHeight = value["BabyHeight"] as? String,
            let babyWeight = value["BabyWeight"] as? String else {
                return nil
        }

        self.key = snapshot?.key
        self.reference = snapshot?.ref
        self.uid = uid

        self.babyURL = babyURL
        self.babyName = babyName
        self.babyHeight = babyHeight
        self.babyWeight = babyWeight
    }

    func getuserData() -> String {
        return ("BabyName =  \(babyName)")
    }
}

func fetchCurrentUserInfo() {
        var currentUserRef = Database.database().reference().child("Users").child("\(userID)")
        handler = currentUserRef.queryOrderedByKey().observe(DataEventType.value, with: { (snapshot) in
            print("User data = \(snapshot.value)")

            let user = UserClass(snapshot: snapshot)
            print(user?.babyName)
            self.babyName.text = user?.babyName
       })
   }

我正在获取user数据,但没有获取user.babyName。我该如何解决?

1 个答案:

答案 0 :(得分:1)

这可能会为您提供帮助,因为没有提到数据库结构。但您必须一个接一个地迭代子项,然后使用for循环从firebase中获取确切的数据。

async actionOne(req, res, next) {
    try {
        await this.actionTwo();
    } catch( error ) => {
       // catch the error
    }
}

async actionTwo(req, res, next) {
    return new Promise( function( resolve, reject ) {
        // do something
        resolve()
    })
    .catch( error ) {
        // handle error
        throw error;
    }
}