Swift

VGVoiceClient

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

NOTE: Notice that, you have already imported VGVoiceClient at the top of the file.

Add a VGVoiceClient instance and a User property, below the connectionStatusLabel.

class ViewController: UIViewController {
    ...
    let connectionStatusLabel = UILabel()
    
    var client = VGVoiceClient()
    
    var user: User? {
        didSet {
            login()
        }
    }
}

Button targets

For the log in buttons to work, you need to add targets to them which will run a function when they are tapped. In the ViewController.swift file add these two functions.

class ViewController: UIViewController {
    ...

    override func viewDidLoad() {
        ...
    }

    ...

    @objc func setUserAsAlice() {
        self.user = User.Alice
    }

    @objc func setUserAsBob() {
        self.user = User.Bob
    }
}

Then link the two functions to their respective buttons at the end of the viewDidLoad function.

override func viewDidLoad() {
    ...

    loginAliceButton.addTarget(self, action: #selector(setUserAsAlice), for: .touchUpInside)
    loginBobButton.addTarget(self, action: #selector(setUserAsBob), for: .touchUpInside)
}

Add the log in function

At the end of ViewController.swift, add the login function needed by the user property. This function creates a session when the user property is set to a new value.

class ViewController: UIViewController {
    ...

    override func viewDidLoad() {
        ...
    }

    func login() {
        guard let user = self.user else { return }

        VGVoiceClient.isUsingCallKit = false
        let config = VGClientConfig(region: .US)
        config.enableWebsocketInvites = true
        client.setConfig(config)
        client.createSession(user.jwt) { error, sessionId in
            DispatchQueue.main.async { [weak self] in
                guard let self else { return }
                if error == nil {
                    self.connectionStatusLabel.text = "Connected"
                } else {
                    self.connectionStatusLabel.text = error?.localizedDescription
                }
            }
        }
    }
    
}

An error is shown if encountered, and the connectionStatusLabel is updated with the relevant connection status.

NOTE: The enableWebsocketInvites flag on the client configuration and the isUsingCallKit setting should not be used in production. Enable push notifications to make sure you get incoming calls even when your application is in the background using CallKit. See the push notifications guide for more information.

Build and Run

Press Cmd + R to build and run again. If you tap on one of the log in buttons it will log the client in with the respective user:

Interface connected