tsteve
tsteve

Reputation: 549

Firebase filling array twice -- Swift

I have two String arrays: one that holds order numbers, and one that holds addresses.

I pull data from Firebase in viewDidAppear using a function that contains the following:

    self.localOrderNumberArray.removeAll()
    self.localAddressArray.removeAll()

    self.orderNumbers.removeAll()
    self.addresses.removeAll()

    self.tableView.reloadData()

    if onItsWayCompanyNameStoreNumberCourierNumberRootRef != nil {

        let deliveryRef = onItsWayCompanyNameStoreNumberCourierNumberRootRef.childByAppendingPath("deliveries")

        deliveryRef.observeEventType(.ChildAdded, withBlock: { snapshot in

            self.orderNumbers.removeAll()
            self.addresses.removeAll()

            print(snapshot.value.objectForKey("orderNumber"))
            let orderNumberPulledFromFirebase = snapshot.value.objectForKey("orderNumber") as! String
            self.localOrderNumberArray.insert(orderNumberPulledFromFirebase, atIndex: 0)

            let addressPulledFromFirebase = snapshot.value.objectForKey("address") as! String
            self.localAddressArray.insert(addressPulledFromFirebase, atIndex: 0)

            self.orderNumbers = self.localOrderNumberArray
            self.addresses = self.localAddressArray

            self.tableView.reloadData()

        })
    }

The function fills a UITableView with the data pulled from Firebase.

Everything works great when I first run the app. I can add data to Firebase through a different function, and the function above will pull the new data into the UITableView just fine.

However, when I segue to a different view controller (another UITableView, in this case), and then come back to the view that holds the function above, the function fills the order number and address arrays twice when I add new data.

If I segue to the other UITableView a second time, and then come back to view that holds the function above, the function fills the order number and address arrays three times when I add new data. And so on and so on.

It's the strangest thing. I can't figure it out, and it's about to drive me over the edge. Please help.

Upvotes: 4

Views: 654

Answers (1)

ArunGJ
ArunGJ

Reputation: 2683

You are calling deliveryRef.observeEventType in viewDidAppear. viewDidAppear will be called each time the ViewController is presented. So when you segue to other ViewController and comes back, viewDidAppear will be called again and deliveryRef.observeEventType is registered again. So effectively there are two listeners doing the same job in your viewController which will add duplicate data to the array.

You have to implement a logic to do observeEventType only once in the ViewController.

Upvotes: 6

Related Questions