So when I'm loading up my App for the first time and I'm adding in my first piece of data, the tableView reloads and the section/rows are added properly, but when I enter in any additional data after that, the new data gets added but my original data gets duplicated in my tableView (not in the backend), furthermore, if I'm adding in data under the same Section, my app crashes and I get the error that I have in my title.
Looking to get some insight on this. This is my first Firestore App and I'm still trying to figure it out.
EDIT 1: I tried removing the two snapshot Listeners and that solved my error problem, but my data still get's duplicated...
EDIT 2: Nevermind. I figured it out. I had the dataArray as a global variable that I kept appending to.
struct Workouts: Decodable {
var workout : String
}
struct Days: Decodable {
var dow : String
var workouts : [Workouts]
}
var dayCount = 0
var dataArray = [Days]()
//MARK: - viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
vcBackgroundImg()
navConAcc()
picker.delegate = self
picker.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
tableView.tableFooterView = UIView()
Auth.auth().addStateDidChangeListener { (auth, user) in
self.userIdRef = user!.uid
self.rootCollection = Firestore.firestore().collection("/users/\(self.userIdRef)/Days")
self.loadData { (Bool) in
if Bool == true {
self.dayCount = self.dataArray.count
self.tableView.reloadData()
}
}
}
}
//MARK: - Load Data
func loadData(completion: @escaping (Bool) -> ()){
let group = DispatchGroup()
self.rootCollection.addSnapshotListener ({ (snapshot, err) in
if let err = err
{
print("Error getting documents: \(err.localizedDescription)");
}
else {
guard let dayDocument = snapshot?.documents else { return }
for day in dayDocument {
group.enter()
self.rootCollection.document(day.documentID).collection("Workouts").addSnapshotListener{(snapshot, err) in
var workouts = [Workouts]()
let workoutDocument = snapshot!.documents
try! workoutDocument.forEach({doc in
let tester: Workouts = try doc.decoded()
let workoutString = tester.workout
let newWorkout = Workouts(workout: workoutString)
workouts.append(newWorkout)
})
let dayTitle = day.data()["dow"] as! String
let newDay = Days(dow: dayTitle, workouts: workouts)
self.dataArray.append(newDay)
group.leave()
}
}
}
group.notify(queue: .main){
completion(true)
}
})
}