2

I am a beginner in iOS development, and I am following one tutorial using firebase database to make a simple chat app. Actually I am confused with the use of viewDidLoad method.

Here is the screenshot of the app: https://ibb.co/gqD4Tw

I don't understand why retrieveMessage() method is put on viewDidLoad when I want to send data (chat message) to firebase database, I used sendButtonPressed() method (which is an IBAction) and when I want to retrieve data from the database, I use retrieveMessage().

The retrieveMessage() method is called on viewDidLoad, as far as I know the viewDidLoad method is called only once after the view is loaded into memory. We usually use it for initial setup.

So, if viewDidLoad is called only once in initial setup, why the retrieveMessage() method can retrieve all the message that I have sent to my own database over and over again, after I send message data to the database ?

I don't understand why retrieveMessage() method is put on viewDidLoad below is the simplified code:

class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


    var messageArray = [Message]()

    @IBOutlet var messageTextfield: UITextField!
    @IBOutlet var messageTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Set as the delegate and datasource :
        messageTableView.delegate = self
        messageTableView.dataSource = self

        //the delegate of the text field:
        messageTextfield.delegate = self

        retrieveMessage()

        ///////////////////////////////////////////

    //MARK: - Send & Recieve from Firebase

    @IBAction func sendPressed(_ sender: AnyObject) {

    // Send the message to Firebase and save it in our database

    let messageDB = FIRDatabase.database().reference().child("message")
    let messageDictionary = ["MessageBody":messageTextfield.text!, "Sender": FIRAuth.auth()?.currentUser?.email]

        messageDB.childByAutoId().setValue(messageDictionary) {
            (error,ref) in

            if error != nil {
                print(error!)
            } else {
                self.messageTextfield.isEnabled = true
                self.sendButton.isEnabled = true
                self.messageTextfield.text = ""
            }   
        }
    }

    //Create the retrieveMessages method :

    func retrieveMessage () {
        let messageDB = FIRDatabase.database().reference().child("message")

        messageDB.observe(.childAdded, with: { (snapshot) in

            let snapshotValue = snapshot.value as! [String:String]

            let text = snapshotValue["MessageBody"]!
            let sender = snapshotValue["Sender"]!

            let message = Message()
            message.messsageBody = text
            message.sender = sender

            self.messageArray.append(message)

            self.messageTableView.reloadData()
        })
    }
}
2
  • Because you added observer in that method thats'y if you add message then it automatically reflected Commented Oct 9, 2017 at 12:36
  • 1
    In retrieveMessage function there is an observe closure, from within that closure messageArray and messageTableView get updated. So in viewDidLoad you only start the observation, from then on the observer updates your data and UI continuously.
    – Au Ris
    Commented Oct 9, 2017 at 12:37

3 Answers 3

5

viewDidLoad method is called only once in ViewController lifecycle.

The reason retrieveMessage() is called in viewDidLoad because it's adding observer to start listening for received and sent message. Once you receive or send message then this block(observer) is called and then adding that text in array self.messageArray.append(message) and updating tableview.

1

viewDidLoad gets called only once but the firebase functions starts a listener, working in background and syncronizeing data. Its called in viewDidLoad because it tells -> When this view loads, start listening for messages.

0

ViewDidLoad() is only called upon initializing the ViewController. If you want to have a function called every time the user looks at the VC again (e.g. after a segue back from another VC) you can just use ViewDidAppear(). It is also called when ViewDidLoad() is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.