mikew
mikew

Reputation: 377

Update tableview instead of entire reload when navigating back to tableview View Controller

I have a home UIViewController that contains a UITableView. On this view controller I display all games for the current user by reading the data from firebase in ViewWillAppear. From this view controller a user can press a button to start a new game and this button takes them to the next view controller to select settings, this then updates the data in firebase and adds a new child. Once they navigate back to the home view controller is there anyway to just update the data with the new child added instead of loading all the games for the table view again as I am currently doing?

This is my current code:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let currentUserID = Auth.auth().currentUser?.uid {
        let gamesRef = Database.database().reference().child("games").child(currentUserID)
        self.games = []

        gamesRef.observeSingleEvent(of: .value, with: { snapshot in
            for child in snapshot.children {
                let game = child as! DataSnapshot
                self.games.append(game)
                self.tableView.reloadData()
            }
        })
    }
}

Upvotes: 0

Views: 405

Answers (1)

3stud1ant3
3stud1ant3

Reputation: 3606

I think you can use observeSingleEvent and .childAdded

You can do the loading of all the data in viewDidLoad and of single child in viewWillAppear since viewDidLoad will be called once initially

Since both methods will be called initially, so we can have a bool flag so we can control which code runs initially and which does not , since viewWillAppear is called after viewDidLoad so we change the value of this flag in viewWillAppear method and then control the execution of code inside viewWillAppear using this flag

class SomeVC: UIViewController {

        var flag = false
        override func viewWillAppear(_ animated: Bool) {
                super.viewWillAppear(animated)
                if flag {
                        //do your work here
                }else {
                   flag = true
                }

        }
}

Edited: Another solution can be that you dont do anything in viewDidLoad and do the work only in viewWillAppear since in this particular scenario data in both calls are related (fetching the data from Firebase)

class SomeVC: UIViewController {

            var flag = false
            override func viewWillAppear(_ animated: Bool) {
                    super.viewWillAppear(animated)
                    if flag {
                            //fetch only one child
                    }else {
                            //fetch all the data initially
                            flag = true
                    }

            }
    }

Upvotes: 3

Related Questions