我有一些连接到firebase的代码,当它到达代码的某个部分时它运行了两次它也没有删除我的waitAlertController它导致我的代码崩溃,因为它运行它两次然后第二次没有值,因为第一次运行它删除它们是我的代码
这是我的表视图,我在其中添加了wait视图控制器并启动了完成方法。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let alertController = UIAlertController(title: "Accept Bet", message: "Match the bet of " + amountBets[indexPath.row], preferredStyle: .alert)
let okButton = UIAlertAction(title: "No", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
let yesButton = UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
// let them know to wait a second or the bet won't go through
var waitController = UIAlertController(title: "Please Wait", message: "Your bet is being processed", preferredStyle: .alert)
self.present(waitController, animated: true, completion: nil)
//take away the usersMoney
self.takeAwayMoney(self.amountBets[indexPath.row],index: indexPath.row, completion: { (result: Bool?) in
guard let boolResult = result else {
return
}
var getResult = ""
print("You have taken away the users money")
print("you made it this far almost there")
//let delayInSeconds = 3.0 // 1
//DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
})
if (self.userHasMoney == true) {
self.updateBet(indexPath.row, completion: { (result: Bool?) in
guard let checkRes = result else {
return
}
})
self.getOpoosingUserNames(self.userName, indexPath.row, completion: { (anothaResult: Bool?) in
guard let value = anothaResult else {
return print("didn't work")
}
//wait for the first view to load in case it uploads to fast
sleep(1)
self.dismiss(animated: true, completion: nil)
let successController = UIAlertController(title: "Success", message: "You have made a bet with " + self.opposingUserNames!, preferredStyle: .alert)
let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
successController.addAction(okButt)
self.present(successController, animated: true, completion: nil)
//lastly delete the opposing UserName
self.amountBets.remove(at: indexPath.row)
self.tableView.reloadData()
print("Second")
})
} else {
//display a alert that lets the user know hes broke
let brokeController = UIAlertController(title: "Failed", message: "Reason: You don't have enough money!", preferredStyle: .alert)
let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
brokeController.addAction(okButt)
self.present(brokeController, animated: true, completion: nil)
}
return
})
alertController.addAction(okButton)
alertController.addAction(yesButton)
present(alertController, animated: true, completion: nil)
}
这是我的takeMoneyAway方法
func takeAwayMoney(_ howMuch: String, index: Int, completion: @escaping (Bool)-> ()) -> Void{
if let notMuch = Int(howMuch) {
let userID = FIRAuth.auth()?.currentUser?.uid
datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let money = value?["money"] as? String ?? ""
//convert money to int
if let conMoney = Int(money) {
var conMoreMoney = conMoney
if conMoreMoney < notMuch {
print(" You don't have enough money")
completion(false)
return
} else {
conMoreMoney -= notMuch
let values = ["money": String(conMoreMoney)]
//update the users money
self.datRef.child("User").child(userID!).updateChildValues(values)
completion(true)
/*
self.updateBet(index, completion: { (result: Bool?) in
guard let checkResult = result else {
return print("Failed to get result")
}
if checkResult == true {
completion(true)
} else {
completion(false)
}
})
*/
}
}
// ...
}) { (error) in
print(error.localizedDescription)
}
}
}
并且我的最终方法会转到我的数据库更新值并抓住他们下注的人。
func updateBet(_ index: Int, completion: @escaping (_ something: Bool?) -> Void) {
let userID = FIRAuth.auth()?.currentUser?.uid
datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
// ...
self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
//
// this is the unique identifier of the bet. eg, -Kfx81GvUxoHpmmMwJ9P
guard let dict = snapshot.value as? [String: AnyHashable] else {
print("failed to get dictionary from Bets.\(self.userName)")
return
}
let values = ["OpposingUsername": self.userName,"Show": "no"]
self.datRef.child("Bets").child(self.tieBetToUser[index]).updateChildValues(values)
let checkTheCodeWentHere = "Success"
// now get the opposing username which is just the Username registered to that specific bet
self.datRef.child("Bets").child(self.tieBetToUser[index]).observeSingleEvent(of: .value, with: { snapshot in
let thisValue = snapshot.value as? NSDictionary
if let username = thisValue?["Username"] as? String {
self.opposingUserNames = username
completion(true)
} else {
completion(false)
}
})
})
}) { (error) in
print(error.localizedDescription)
}
}
所以在tableview方法中有一段代码表明checkRes == true {} 花括号中的所有代码都运行了两次我用断点检查了这个,有人可以告诉我为什么会这样吗?
答案 0 :(得分:1)
如果无法实际运行代码并对其进行测试,并且完全基于您上面的评论,我相信您所谈论的部分就是:
//take away the usersMoney
self.takeAwayMoney(self.amountBets[indexPath.row],index: indexPath.row, completion:{(result) in
if result {
// User has money
} else {
// User does not have money
}
var getResult = ""
print("You have taken away the users money")
print("you made it this far almost there")
//let delayInSeconds = 3.0 // 1
//DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
})
takeAwayMoney
方法通过闭包的result
参数返回用户是否有钱,并且该参数在方法定义中不是可选的。但是,在上面的代码中,由于某种原因,它被声明为可选的。我已更改代码以删除该位代码,并添加了if
条件,指示在takeAwayMoney
执行后如何继续。
基本上,您首先调用takeAwayMoney
,等待该方法通过闭包返回其结果,然后查看闭包的结果并进行任何后续处理。因此,看起来您确实需要将if (self.userHasMoney == true) {
条件中的所有代码移动到takeAwayMoney
完成闭包内。
希望这是有道理的。如果没有,请随意ping我,我会尽力澄清。