Swift

VGChatClient

Before you can start a chat, the Client SDK needs to authenticate to the Vonage servers. The following additions are required to ContentView.swift.

At the top of the file, import VonageClientSDKChat:

import SwiftUI
import VonageClientSDKChat

Create a new class at the bottom of the file called LoginViewModel:

@MainActor
final class LoginViewModel: ObservableObject {
    @Published var error = ""
    @Published var isError = false
    @Published var isLoggedIn = false
    
    private let aliceJwt = "ALICE_JWT"
    private let bobJwt = "BOB_JWT"
    
    let client = VGChatClient()
    
    func login(_ username: String) async {
        do {
            let jwt = username == "Alice" ? aliceJwt : bobJwt
            try await client.createSession(jwt)
            isLoggedIn = true
        } catch {
            self.error = error.localizedDescription
            self.isError = true
        }
    }
}

This class will create an instance of VGChatClient then create a session using a JWT. Replace ALICE_JWT and BOB_JWT with the JWTs you created earlier.

Button Actions

For the log in buttons to work, you need to add actions to them which will run a function when they are tapped. Update the view code to instantiate a LoginViewModel object and call its login function:

struct ContentView: View {
    @StateObject private var loginModel = LoginViewModel()
    
    var body: some View {
        NavigationStack {
            VStack {
                Button("Login as Alice") {
                    Task {
                        await loginModel.login("Alice")
                    }
                }.buttonStyle(.bordered)
                Button("Login as Bob") {
                    Task {
                        await loginModel.login("Bob")
                    }
                }.buttonStyle(.bordered)
            }
            .padding()
            .navigationDestination(isPresented: $loginModel.isLoggedIn) {
                let chatViewModel = ChatViewModel(client: loginModel.client)
                ChatView(chatViewModel: chatViewModel)
            }
        }.alert(isPresented: $loginModel.isError) {
            Alert(title: Text(loginModel.error))
        }
    }
}

If there is an error when creating a session, an Alert will be presented with the error message. There is also a navigationDestination destination which will open the chat screen if the session is created successfully. You will build that in the next step.