Swift

Testing your Code

At this point, your VonageVideoSDK.swift file should look something like this (with a few adjustments):

import OpenTok

// Replace with your Application ID
let kApiKey = ""
// Replace with your generated session ID
let kSessionId = ""
// Replace with your generated token
let kToken = ""

struct Signal: Identifiable {
  let id = UUID()
  let text: String
  let isUsers: Bool
}

class VonageVideoSDK: NSObject {
    @Published var isSessionConnected = false
    @Published var messages: [Signal] = []

    lazy var session: OTSession = {
        return OTSession(apiKey: kApiKey, sessionId: kSessionId, delegate: self)!
    }()
    
    override init() {
        super.init()
        var error: OTError?
        session.connect(withToken: kToken, error: &error)
        if let error = error {
            print("Session creation error \(error.description)")
        }
    }
    
    func sendSignal(type: String, data: String) {
        var error: OTError?
        session.signal(withType: type , string: data, connection: nil, error: &error)
        if let error = error {
            print("Session creation error \(error.description)")
        } else {
            messages.append(.init(text: data, isUsers: true))
        }
    }
   
 }

// MARK: - OTSession delegate callbacks
extension VonageVideoSDK: OTSessionDelegate {
    func sessionDidConnect(_ session: OTSession) {
       isSessionConnected = true
    }
    
    func sessionDidDisconnect(_ session: OTSession) {
        isSessionConnected = false
    }
    
    func session(_ session: OTSession, didFailWithError error: OTError) {
        print("Session Failed to connect: \(error.localizedDescription)")
    }
    
    func session(_ session: OTSession, receivedSignalType type: String?, from connection: OTConnection?, with string: String?) {
        if let string = string, let type = type, let connection = connection {
            guard type == "msg" else { return }
            guard connection.connectionId != self.session.connection?.connectionId else { return }
            messages.append(.init(text: string, isUsers: false))
        }
    }
    
    func session(_ session: OTSession, streamCreated stream: OTStream) {}
    
    func session(_ session: OTSession, streamDestroyed stream: OTStream) {}
}

In your completed code, you should have hard coded values to replace YOUR_APP_ID, YOUR_SESSION_ID and YOUR_TOKEN — if you haven't done this, see Setting up authentication above.

Your ContentView.swift file should look like this:

import SwiftUI

struct ContentView: View {
    @StateObject private var sdk = VonageVideoSDK()
    @State private var message: String = ""
    
    var body: some View {
        VStack {
            if (sdk.isSessionConnected) {
                List(sdk.messages) { signal in
                    Text(signal.text)
                        .listRowSeparator(.hidden)
                        .frame(maxWidth: .infinity, alignment: signal.isUsers ? .trailing : .leading)
                }
                HStack {
                    TextField("Message", text: $message)
                    Button("Send") {
                        sdk.sendSignal(type: "msg", data: message)
                        self.message = ""
                    }.buttonStyle(.bordered)
                }.padding(8)
            } else {
                ProgressView {
                    Text("Connecting ...")
                        .font(.title)
                }
            }
        }
    }
}
  1. Build and run the app in Xcode (CMD + R).
  2. Enter some text into the textfield and send it.
  3. You should see the message get added to the message history.

Next, we can test what it looks like if someone else sends a message. We can simulate that by running the app again on a different simulator/device:

  1. Build and run the app on a different simulator.
  2. Reopen the app on the original simulator.
  3. Enter some text into the textfield and send it on both simulators.
  4. You should see a both messages get added to the message history.

Troubleshooting tip: If you cant connect to the session, check the Xcode console for errors. The most likely issue is that your API key, session ID, or token is not set up properly. Since you hard coded your credentials, it's also possible that your token has expired.

Basic text chat

Follow this tutorial to build basic text chat from scratch using the Vonage Video API. It is the quickest way to build a proof of concept for this functionality on the video platform.

以下の言語で利用可能:
JavaScript Java Swift
手順
1
Overview
2
Before You Begin
3
Configure a Vonage Video Application
4
Creating the Project
5
Setting Up Authentication
6
Connecting to the Session
7
Sending a Signal
8
Receiving a Signal
9
Testing your Code
10
Conclusion