Reputation: 123
I have a problem when i try to get value of isBusy property from my database. A used breakpoints and it even doesn't go to instruction where i assign a value for isBusy, it assigns empty string and goes to else condition.
if docChild == 0 {
let selectedDoctor = Doctors.doc1
var isBusy = String()
databaseHandle = reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.isBusy).observe(.childAdded, with: { (snapshot) in
isBusy = snapshot.value as! String
})
if isBusy == "false" {
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.isBusy).setValue("true")
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.firstname).setValue(firstNameLabel.text)
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.lastname).setValue(lastNameLabel.text)
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.pesel).setValue(peselLabel.text)
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.telephone).setValue(phoneLabel.text)
} else {
createAlert(title: "Przepraszamy - termin jest zajęty", message: "Proszę wybrać inny termin")
}
Upvotes: 0
Views: 71
Reputation: 127034
The answer is fairly simply. Firebase Database requests are asynchronous, so that at the time you reach your if isBusy == "false"
statement the value did not get fetched from the Database. Change your code accordingly:
if docChild == 0 {
let selectedDoctor = Doctors.doc1
var isBusy = String()
databaseHandle = reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.isBusy).observe(.childAdded, with: { (snapshot) in
isBusy = snapshot.value as! String
if isBusy == "false" {
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.isBusy).setValue("true")
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.firstname).setValue(firstNameLabel.text)
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.lastname).setValue(lastNameLabel.text)
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.pesel).setValue(peselLabel.text)
reference.child(selectedDoctor).child(dateChild).child(timeChild).child(ReservationFields.telephone).setValue(phoneLabel.text)
} else {
createAlert(title: "Przepraszamy - termin jest zajęty", message: "Proszę wybrać inny termin")
}
})
As you can see I simply moved your code into the handler, so it gets executed after your value has been fetched.
Upvotes: 1