Swift

Building the chat interface

To be able to chat, you will need to create a new View for the chat interface. From the Xcode menu, select File > New > File.... Choose a SwiftUI View, name it ChatView. This will create a new file called ChatView.swift, at the top import VonageClientSDKChat:

import SwiftUI
import VonageClientSDKChat

Next you will create the ChatViewModel.

ChatViewModel

The ChatViewModel will handle the handle send and retrieving events from the conversation. At the bottom of the ChatView.swift file, create the view model:

@MainActor
final class ChatViewModel: NSObject, ObservableObject {
    private let conversationID = "CON_ID"
    
    private var client: VGChatClient
    private var memberID: String?
    
    @Published var events: [VGPersistentConversationEvent] = []
    
    init(client: VGChatClient) {
        self.client = client
        super.init()
        client.delegate = self
    }   
}

extension ChatViewModel: VGChatClientDelegate {
    nonisolated func chatClient(_ client: VGChatClient, didReceiveConversationEvent event: VGConversationEvent) {}
    
    nonisolated func client(_ client: VGBaseClient, didReceiveSessionErrorWith reason: VGSessionErrorReason) {}
}

The view model has properties for the conversation ID, the chat client and the member ID. The chat client will be passed in from the login screen so it will already be authenticated. Replace the CON_ID placeholder with the conversation ID you created earlier. The VGChatClientDelegate is added but will be implemented in a later stage.

Create UI

Now that the skeleton ChatViewModel is created, you can update the ChatView to have a TextField for entering a message, a Button for sending the message and a list for displaying messages.

struct ChatView: View {
    @StateObject var chatViewModel: ChatViewModel
    @State private var message: String = ""
    
    var body: some View {
        VStack {
            VStack {
                List {
                    ForEach(chatViewModel.events, id: \.id) { event in
                        switch event.kind {
                        default:
                            EmptyView()
                        }
                    }.listRowSeparator(.hidden)
                }.listStyle(.plain)
                
                Spacer()
                
                HStack {
                    TextField("Message", text: $message)
                    Button("Send") {
                        Task {
                            
                        }
                    }.buttonStyle(.bordered)
                }.padding(8)
            }
        }
    }
}

Build and Run

Run the project again (Cmd + R) to launch it in the simulator. If you log in with one of the users you will see the chat interface

Chat interface