将firebase数据库值转换为Int

时间:2017-03-26 23:54:45

标签: swift firebase casting firebase-realtime-database

在我的应用程序中,人们可以对他们认为将赢得哪支球队下注。当他们去打赌时,应该将一些东西上传到数据库。首先是下注者的用户名。这是什么赌注(它是赌两次下注三次赌注)并且它应该显示赌注是由哪支球队。

问题我已经把赌注变成了一个Int,这样我每次有人下注时都可以增加赌注,这样他们就有了一个独特的赌注。

下面我会解释一些事情,因为我的代码因为测试目的而混乱不堪。

在viewDidLoad方法中,我有办法收集用户名和有人做了多少赌注。在数据库中,它默认为字符串“0”。

现在打赌self.betNumber应该具有值“0”

然后在submitData函数中我安全地获取betNumber并将其转换为Int然后将该值赋给全局声明的变量bets

然后我将赌注增加1 之后,我尝试将self.bets转换为String,但作为子项将其转换为数据库

这是我收到错误的地方

import UIKit
import Foundation
import Firebase


class addBets: UIViewController {
    let betRef = FIRDatabase.database().reference(fromURL: "not showing these sorry")
    let userRef = FIRDatabase.database().reference(fromURL: "")
    let ref = FIRDatabase.database().reference(fromURL: "")
    let currentUser = FIRAuth.auth()?.currentUser


    @IBOutlet weak var teamOneLabelAdd: UILabel!
    @IBOutlet weak var teamTwoLabelAdd: UILabel!

    @IBOutlet weak var teamOneBet: UITextField!

    @IBOutlet weak var teamTwoBet: UITextField!



    var userName: String!
    var teamOne: String!
    var teamTwo = String()

    var betNumber: String!
    var bets: Int = 0




    var teamOneBetAnotherOne: String!
    var teamOneBetAnotherTwo: String!
    override func viewDidLoad() {
        super.viewDidLoad()
        teamOneLabelAdd.text = teamOne
        teamTwoLabelAdd.text = teamTwo


        //Looks for single or multiple taps.
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")

        //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
        tap.cancelsTouchesInView = false

        view.addGestureRecognizer(tap)

        //self.teamOneBet.delegate = self
        //self.teamTwoBet.delegate = self

        let userID = FIRAuth.auth()?.currentUser?.uid
        ref.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            let username = value?["username"] as? String ?? ""
            self.userName = username
            let betnumber = value?["bets"] as? String ?? ""
            self.betNumber = betnumber




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


    }

    func textFieldShouldReturn(userText: UITextField!) -> Bool {
        teamOneBet.resignFirstResponder()
        teamTwoBet.resignFirstResponder()
        return true
    }


    func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }

    @IBAction func submitData(_ sender: Any) {
        // get the userName to tell who is doing the bet and set it as a key

        sleep(4)

        if let usernamee = self.userName {
            if let anotherBet = self.betNumber as? Int {
                self.bets = anotherBet
            }
            self.bets += 1

            let usableBets = self.bets as? String ?? ""

            let useRef = self.ref.child("Bets").child(usernamee).child(self.bets as? String ?? "")

            var values = ["Username": usernamee,"Bet": "0", "ForTeam": ""]
            if let betOne = self.teamOneBet.text{

                if betOne == "" {

                } else {
                    values["Bet"] = betOne
                    values["ForTeam"] = teamOneLabelAdd.text
                }
            }
            if let betTwo = self.teamTwoBet.text{

                if betTwo == "" {

                } else {
                    values["Bet"] = betTwo
                    values["ForTeam"] = teamTwoLabelAdd.text
                }
            }


        //self.betRef.child("Bets").setValue(self.userName)
        if let worked = currentUser?.getTokenWithCompletion() {

            useRef.setValue(values)
            /*
            useRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
                if (error != nil) {
                    print(error!)
                    return

                }

            })
            */



        }


         self.navigationController?.popViewController(animated: true)

        }







    }

    func getUserName() {
        let userID = FIRAuth.auth()?.currentUser?.uid
        ref.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            let username = value?["username"] as? String ?? ""
            self.userName = username

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


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //let indexPath = self.tableView.indexPathForSelectedRow!
        //var DestViewController : addBets = segue.destination as! addBets
        //DestViewController.teamOne = self.teamOne.text!
        //DestViewController.teamOne = self.teamTTwo

        if segue.identifier == "gotobetview" {
            if let destination = segue.destination as? BetView {

                //destination.userNames = self.teamOne.text! as? String

                //destination.teamTwo = (self.teamTwo.text! as? String)!
            }
        }

    }

}

这里是firebase结构,我提取的数据来自“用户”,我写的数据是“Bets”

enter image description here

1 个答案:

答案 0 :(得分:2)

从粗略看一下你的代码,看起来错误就在这一行:

let useRef = self.ref.child("Bets").child(usernamee).child(self.bets as? String ?? "")

我不完全确定您希望在哪个位置发布用户所下的赌注,但这样做的目的是在下注为1时将useRef设置为位于Bets.\(usernamee).1的孩子,{当赌注是2时等{1}}

如果您希望每次下注都是唯一的,则只需将Bets.\(usernamee).2更改为:

即可
useRef

这将在firebase中创建一个新的条目,如下所示:

let useRef = self.ref.child("Bets").child(usernamee).childByAutoId()

所以现在的问题是如何获得投注?那么这实际上非常简单,因为每一个都是唯一标识的:

Bets:
    usernameyoyo:
        -Kfx81GvUxoHpmmMwJ9P:
            Bet: "300",
            ForTeam: "Natus Vincere",
            Username: "usernameyoyo"