I'm trying to break out of this listener once this condition if myDay == self.daysOfWeek[self.picker.selectedRow(inComponent: 0)]
is met, but I'm not getting the results that I'm looking for.
Once the condition is met, it just continues to loop through all the documents. How do I code this up properly?
let addAction = UIAlertAction(title: "Add Workout", style: .default) { (UIAlertAction) in
if self.dayCount != 0 {
print("\(self.dayCount)")
self.colRef.addSnapshotListener { (querySnapshot, err) in
if let err = err
{
print("Error getting documents: \(err)");
}
else
{
for document in querySnapshot!.documents {
let myData = document.data()
let myDay = myData["dow"] as? String ?? ""
print(self.daysOfWeek[self.picker.selectedRow(inComponent: 0)])
print(myDay)
if myDay == self.daysOfWeek[self.picker.selectedRow(inComponent: 0)] {
containsDay = true
print(containsDay)
dayId = document.documentID
workoutColRef = Firestore.firestore().collection("/users/\(self.userIdRef)/Days/\(dayId)/Workouts/")
break //This Break needs to be somewhere else???
}
}
}
}
if containsDay == true {
//Create new workout and store within the selectedDay.
workoutColRef.addDocument(data: ["workout" : "\(self.textField2.text!)", "dayRef" : "\(dayId)"])
self.loadDays()
} else {
//Create new day as well as a new workout, and store the workout within the day.
let newDayRef = self.colRef.addDocument(data: ["dow" : "\(self.daysOfWeek[self.picker.selectedRow(inComponent: 0)])"])
Firestore.firestore().collection("/users/\(self.userIdRef)/Days/\(newDayRef.documentID)/Workouts/").addDocument(data: ["workout" : "\(self.textField2.text!)", "dayRef" : newDayRef])
newDayRef.getDocument { (docSnapshot, err) in
if let err = err
{
print("Error getting documents: \(err)");
}
else
{
let myData = docSnapshot!.data()
let myDay = myData!["dow"] as? String ?? ""
self.daysArray.append(myDay)
}
}
self.dayIdArray.append(newDayRef.documentID)
self.loadDays()
}
} else {
self.dayCount += 1 //If there are no days/workouts, we create new day as well as a new workout, and store the workout within the day.
let newDayRef = self.colRef.addDocument(data: ["dow" : "\(self.daysOfWeek[self.picker.selectedRow(inComponent: 0)])"])
Firestore.firestore().collection("/users/\(self.userIdRef)/Days/\(newDayRef.documentID)/Workouts/").addDocument(data: ["workout" : "\(self.textField2.text!)", "dayRef" : newDayRef])
newDayRef.getDocument { (docSnapshot, err) in
if let err = err
{
print("Error getting documents: \(err)");
}
else
{
let myData = docSnapshot!.data()
let myDay = myData!["dow"] as? String ?? ""
self.daysArray.append(myDay)
}
}
self.dayIdArray.append(newDayRef.documentID)
self.loadDays()
}
}