set value of user rating to Firebase Database

徘徊边缘 提交于 2019-12-25 01:14:46

问题


I try to send the voting from users to firebase and save them under the specific user.

class User: NSObject {
    var id: String?

    init(dictionary: [String: AnyObject]) {
        self.id = dictionary["id"] as? String
    }

    var ref: DatabaseReference!
    var numberOfGood = 0

    init(id: String? = nil) {
        self.id = id
        ref = Database.database().reference().child("users").childByAutoId()
    }

    init(snapshot: DataSnapshot){
        ref = snapshot.ref
        if let value = snapshot.value as? [String : Any] {
            numberOfGood = value["numberOfGood"] as! Int
        }
    }

    func save() {
        let postDictionary = [
            "id" : self.id,
            "numberOfGood" : self.numberOfGood,
            ] as [String : Any]
        self.ref.setValue(postDictionary)
    }
}

Inside the viewController where to vote I handle the voting itself like this:

class UserRatingClass {
    var numberOfGood = 0

    var ref = Database.database().reference().child("users").childByAutoId()

    func good() {
        numberOfGood += 1
        ref.child("numberOfGood").setValue(numberOfGood)
    }
}

var userRating: UserRatingClass! {
    didSet {
        let x = userRating.numberOfGood

        self.good.setTitle("\(x) 👍", for: [])

    }
}

 @IBAction func goodReview(_ sender: UIButton) {
    userRating.good()
    let x = userRating.numberOfGood
    self.good.setTitle("\(x) 👍", for: [])
}

I tried different ways like

    var StringGood = String(user?.numberOfGood)
    self.ref.child("users").child(StringGood).setValue(x)

inside the buttonActionFunction but by this I'm always getting Cannot invoke initializer for type 'String' with an argument list of type '(Int?)' as an error...

Edit: I call the User.swift class like this:

var user: User?

来源:https://stackoverflow.com/questions/59236420/set-value-of-user-rating-to-firebase-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!