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()
})
}
}
retrieveMessage
function there is anobserve
closure, from within that closuremessageArray
andmessageTableView
get updated. So inviewDidLoad
you only start the observation, from then on the observer updates your data and UI continuously.