Swift

Create the Screen Capturer

The Vonage SDK expects a custom video capturer that conforms to OTVideoCapture. Create a new file ScreenCapturer.swift and implement:

  1. Store a reference to the view to capture – even though our app is set up in SwiftUI, the simplest way to do it is with UIView which we will pass to the Capturer, alternatively this can be done with a UIViewRepresentable wrapper.
  2. Render the view periodically – use drawHierarchy(in:afterScreenUpdates:).
  3. Convert to CVPixelBuffer / OTVideoFrame – and pass frames to videoCaptureConsumer.

Capture a view

import Foundation
import UIKit
import OpenTok

class ScreenCapturer: NSObject, OTVideoCapture {
    var videoContentHint: OTVideoContentHint
    var videoCaptureConsumer: OTVideoCaptureConsumer?

    private let captureView: UIView
    private let captureQueue = DispatchQueue(label: "screen-capture")
    private var timer: DispatchSourceTimer
    private var capturing = false
    private var videoFrame: OTVideoFrame
    private var pixelBuffer: CVPixelBuffer?

    init(withView view: UIView) {
        self.videoContentHint = .none
        self.captureView = view
        self.timer = DispatchSource.makeTimerSource(flags: .strict, queue: captureQueue)
        self.videoFrame = OTVideoFrame(format: OTVideoFormat(argbWithWidth: 0, height: 0))
    }

    private func captureFrame() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(captureView.bounds.size, false, 0)
        defer { UIGraphicsEndImageContext() }
        captureView.drawHierarchy(in: captureView.bounds, afterScreenUpdates: false)
        return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
    }

    // Implement initCapture, start, stop, releaseCapture, isCaptureStarted, captureSettings
    // and feed frames to videoCaptureConsumer. See ScreenCapturer.swift for full implementation.
}

Copy the full ScreenCapturer.swift implementation from this sample project. It handles:

  • Timer-based capture at ~10 fps
  • Resizing and padding for encoder compatibility
  • CVPixelBuffer creation and OTVideoFrame delivery