从Firebase Table Swift获取用户用户名

时间:2020-04-14 14:15:45

标签: swift firebase firebase-realtime-database

我正在尝试使用posts表中的post uid从users表中获取用户名,以便将其显示在Feed中。

这是我正在使用的代码。我已经尝试了一段时间,却无法解决它,什么都没显示,但是它在控制台中显示了用户名

final class Post: ListDiffable {


    // 1

    let strainId: String
    let postId: String
    let timestamp: NSNumber
    let caption: String
    let likes: Int
    var user = UserStruct()
    var uid = String()
    var date = String()
    var location = String()
    var data = [ImageDataStruct]()
    var username = String()


    // 2
    init(postId : String, timestamp: NSNumber, caption:String, strainId:String , likes: Int , profilePhoto: URL , uid:String , data:[ImageDataStruct] , user: UserStruct ) {


        self.timestamp = timestamp
        self.likes = likes
        self.caption = caption
        self.postId = postId
        self.strainId = strainId
        self.uid = uid

        self.user = user

        self.data = data


    }

    init(snap: DataSnapshot) {

        let userDict = snap.value as! [String:Any]

        self.likes = userDict["likes"] as! Int
        self.postId = userDict["productId"] as! String
        self.uid = userDict["userID"] as! String
        self.caption = userDict["caption"] as! String
        self.timestamp = userDict["timestamp"] as! NSNumber
        self.date = userDict["date"] as! String
        self.location = userDict["location"] as! String
        self.strainId = userDict["strainid"] as! String
        let productImages = userDict["productImages"] as! [[String:String]]

        var imgStruct = [ImageDataStruct]()

        for data in productImages {


            let dict = data as! [String:String]

            var temp = ImageDataStruct()

            temp.size = dict["size"] as? String
            temp.type = dict["type"] as? String
            temp.url = dict["url"] as? String

            imgStruct.append(temp)
        }

        print(uid)

        Database.database().reference().child("Users").child(uid).observeSingleEvent(of: .value, with: { [weak self] snapshot in

            let user = User(snap: snapshot)

            self?.username = user.userID
            self?.user.username = self?.username

        })



    }



    func diffIdentifier() -> NSObjectProtocol {
        // 1
        return (postId ) as NSObjectProtocol
    }

    // 2
    func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
        return true
    }
}

请有人帮忙!

0 个答案:

没有答案