Swift

Sending a message

In the previous step you learned about conversations and events, sending a message creates a new event and sends it via the client.

To send a message, update the Task in the Button in the view:

struct ChatView: View {
    ...
    HStack {
        TextField("Message", text: $message)
        Button("Send") {
            Task {
                await chatViewModel.sendMessage(message)
                self.message = ""
            }
        }.buttonStyle(.bordered)
    }.padding(8)
}

This will call a sendMessage function on the ChatViewModel that you will create next, then it sets message to an empty string which will clear the inputted text. Next add sendMessage to the ChatViewModel class:

@MainActor
final class ChatViewModel: NSObject, ObservableObject {
    ...
    func sendMessage(_ message: String) async {
        _ = try? await client.sendMessageTextEvent(conversationID, text: message)
    }
}

To send a text message you call sendMessageTextEvent on the client with the conversation ID and the message. If successful, didReceiveConversationEvent on the VGChatClientDelegate will be called. This will append the event to the events array which will automatically update the UI.

Build and Run

Cmd + R to build and run again. You now have a functioning chat app! To chat simultaneously you can run the app on two different simulators/devices:

Sent messages