# 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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mitter.io/getting-started/build-your-first-ios-app/channel-window.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
