Channel Window

This ChannelWindowViewController contains a TableView to display a list of Messages, a UITextField to input a Message and a Send UIButton to send the Text Message.

To initialise the list of Messages, do the following:

// The channel id for this Channel. This will be set by ChannelListViewController
var channelId = String()

// The list of Messages in this channel, backing the messages TableView
var messages = [Message]()

override func viewDidLoad() {
    // Get the AppDelegate, which contains the Mitter object
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    
    // TableView setup
    ...
    
    // Hook up the Send button
    sendButton.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
    
    // Fetch all Messages in Channel
    appDelegate.mitter.messaging.getMessagesInChannel(channelId) {
        result in
            switch result {
            case .success(let fetchedMessages):
                self.messages = fetchedMessages.reversed()
                self.tableView.reloadData()
            case .error:
                print("Couldn't fetch messages")
            }
        }
    }
}

Set up the Send button click target:

@objc func buttonClicked() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    appDelegate.mitter.messaging.sendTextMessage(forChannel: channelId, inputText.text!) { result in
        switch result {
        case .success:
            print("Message sent!")
        case .error:
            print("Couldn't send message")
        }
    }
}

Add a public function to add a Message into the TableView. This will be used by AppDelegate when it receives an FCM message:

func newMessage(channelId: String, message: Message) {
    if (self.channelId == channelId) {
        messages.append(message)
        tableView.reloadData()
    }
}

The controller also contains some View manipulation logic to align/colour Message bubbles based on who the sender is. Refer to the cellForRowAt delegate function for the same.

Last updated