[All posts](/en/blog/)

[Developer](/en/category/developer/)

July 17, 2023

4 min read

# A SwiftUI Solution to Video Streaming

Discover how to enhance your SwiftUI app development by incorporating live streaming capabilities. Explore the challenges of live streaming in SwiftUI and uncover a new solution for seamless integration, empowering you to create captivating live streaming applications.

Max Cobb

Author

![A SwiftUI Solution to Video Streaming](/_assets/assets/agoras-website-assets/images/66733174e5d727f5db428719_swiftui-video-streaming-agora.jpeg)

[All posts](/en/blog/)

On this page

1. [Overview](#overview)

2. [The Challenge of Live Streaming in SwiftUI](#the-challenge-of-live-streaming-in-swiftui)

3. [A SwiftUI Live Streaming Solution](#a-swiftui-live-streaming-solution)

4. [Key Classes of SwiftUIRtc](#key-classes-of-swiftuirtc)

5. [AgoraManager](#agoramanager)

6. [AgoraVideoCanvasView](#agoravideocanvasview)

7. [Example](#example)

8. [Extending SwiftUIRtc](#h-extending-swiftuirtc)

9. [Conclusion](#conclusion)

## Overview

SwiftUI has emerged as a game-changer in app development, providing a modern and intuitive way to build user interfaces for various Apple platforms. While SwiftUI offers tremendous capabilities, there is a noticeable absence of robust solutions for [live streaming](/en/use-cases/media-and-entertainment/) applications. However, the SwiftUIRtc package fills this gap by offering a seamless integration of live streaming capabilities in SwiftUI. In this article, we explore how SwiftUIRtc empowers developers to create compelling live streaming applications using the power of SwiftUI.

## The Challenge of Live Streaming in SwiftUI

Live streaming poses unique challenges in terms of real-time video rendering, media synchronization, and interactive features. SwiftUI, although a powerful UI framework, lacks native support for live streaming components. Developers often face the daunting task of integrating third-party libraries and complex workarounds using UIViewRespresentable over and over again to achieve live streaming functionality in their SwiftUI apps.

## A SwiftUI Live Streaming Solution

The package [`SwiftUIRtc`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc) is designed to address awkward workarounds needed for live streaming in SwiftUI. It provides a small set of tools and SwiftUI components that enable developers to effortlessly incorporate live streaming capabilities into their SwiftUI applications. By leveraging [`SwiftUIRtc`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc) , developers can overcome the hurdles associated with live streaming integration and focus on delivering an exceptional streaming experience to their users.

The package uses the Agora Video RTC engine under the hood to ensure that the best network is used for this solution.

## Key Classes of SwiftUIRtc

Although the SwiftUIRtc package is relatively light by design, its limited classes and methods are everything developers need to start working with live streaming applications right away.

## AgoraManager

[`AgoraManager`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoramanager) has several very important responsibilities, including session management and connection handling. [`AgoraManager`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoramanager) will keep track of the users who join and leave the channel so that you as the developer know what IDs you need to render the video for. These IDs are tracked using delegate methods from the Agora RTC engine which stores them in a published variable, [`allUsers`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoramanager/allusers) .

Join and leave channel methods:

- [`joinChannel(_:token:uid:info:)`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoramanager/joinchannel(_:token:uid:info:))

- [`leaveChannel(leaveChannelBlock:destroyEngine:)`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoramanager/leavechannel(leavechannelblock:destroyengine:))

Implemented delegate methods:

- [`rtcEngine(_:didJoinedOfUid:elapsed:)`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoramanager/rtcengine(_:didjoinedofuid:elapsed:))

- [`rtcEngine(_:didOfflineOfUid:reason:)`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoramanager/rtcengine(_:didofflineofuid:reason:))

## AgoraVideoCanvasView

[`AgoraVideoCanvasView`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoravideocanvasview) is a UIViewRepresentable struct that provides a view for displaying remote or local video in an Agora RTC session. With access to the engine through [`AgoraManager`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoramanager) , [`AgoraVideoCanvasView`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoravideocanvasview) displays local and remote video streams when provided with just a desired ID.

### Example

Using just the two classes described above, we can easily add an AgoraManager that keeps track of all the users in the scene and an AgoraVideoCanvasView for each user listed in the allUsers property as follows:

```
import SwiftUIRtc
import AgoraRtcKit

struct ScrollingVideoCallView: View {
    @ObservedObject var agoraManager = AgoraManager(appId: <#AppId#>, role: .broadcaster)
    var channelId: String = "test"
    var body: some View {
        ScrollView {
            VStack {
                ForEach(Array(agoraManager.allUsers), id: \.self) { uid in
                    AgoraVideoCanvasView(manager: agoraManager, uid: uid)
                        .aspectRatio(contentMode: .fit).cornerRadius(10)
                }
            }.padding(20)
        }.onAppear {
            agoraManager.joinChannel(channelId, token: <#Agora Temp Token#>)
        }.onDisappear {
            agoraManager.leaveChannel()
        }
    }
}
```

When displayed in a ScrollView as above, the different video feeds will automatically appear in a scrolling list view, scaling to however many users join the channel.

## Extending SwiftUIRtc

All of the methods in AgoraManager and AgoraVideoCanvasView are marked as `open`, and the library is open source. That means that each of these classes can be extended with subclasses to add functionality tailored to the exact needs of any SwiftUI application.

For example, if you need to record the quality of incoming streams, you can subclass AgoraManager as follows:

```
public class CallQualityManager: AgoraManager {
    /// A dictionary mapping user IDs to call quality statistics.
    @Published public var callQualities: [UInt: String] = [:]
}
```

And add a couple of additional delegate methods:

```
extension CallQualityManager {
    public func rtcEngine(_ engine: AgoraRtcEngineKit, remoteVideoStats stats: AgoraRtcRemoteVideoStats) {
        self.callQualities[stats.uid] = """
        Received Bitrate = \(stats.receivedBitrate)
        Frame = \(stats.width)x\(stats.height), \(stats.receivedFrameRate)fps
        Frame Loss Rate = \(stats.frameLossRate)
        Packet Loss Rate = \(stats.packetLossRate)
        """
    }

    public func rtcEngine(_ engine: AgoraRtcEngineKit, localVideoStats stats: AgoraRtcLocalVideoStats, sourceType: AgoraVideoSourceType) {
        self.callQualities[self.localUserId] = """
        Captured Frame = \(stats.captureFrameWidth)x\(stats.captureFrameHeight), \(stats.captureFrameRate)fps
        Encoded Frame = \(stats.encodedFrameWidth)x\(stats.encodedFrameHeight), \(stats.encoderOutputFrameRate)fps
        Sent Data = \(stats.sentFrameRate)fps, bitrate: \(stats.sentBitrate)
        Packet Loss Rate = \(stats.txPacketLossRate)
        """
    }
}
```

‍

[`AgoraVideoCanvasView`](https://agoraio-community.github.io/SwiftUIRtc/documentation/swiftuirtc/agoravideocanvasview)

```
AgoraVideoCanvasView(manager: agoraManager, uid: uid)
    .aspectRatio(contentMode: .fit).cornerRadius(10)
    .overlay(alignment: .topLeading) {
        Text(agoraManager.callQualities[uid] ?? "no data").padding()
    }
```

‍

![SwiftUI Video Streaming screenshot](/_assets/assets/agoras-website-assets/images/6669db92d4be74ceccbc4a49_swiftui-video-streaming-agora-1-473x1024.webp)

## Conclusion

SwiftUIRtc brings simplicity and ease of use to the process of integrating live streaming capabilities into SwiftUI applications. By leveraging AgoraManager and AgoraVideoCanvasView, you can add video streams through the Agora RTC SDK, without having to deal with non-SwiftUI classes.

Use SwiftUIRtc in your iOS applications today by adding the package with:

`https://github.com/AgoraIO-Community/SwiftUIRtc.git`

## Related use cases

- [Use case Media & Entertainment Explore use case](/en/use-cases/media-and-entertainment/)

Share

## Keep reading

[![Streaming Videos in Your Livestream Using the Agora Cloud Player](/_assets/assets/agoras-website-assets/images/667330f062447151523ce05a_streaming-videos-in-your-livestream-using-the-agora-cloud-player-agora.png) Developer March 14, 2022 Streaming Videos in Your Livestream Using the Agora Cloud Player Learn how to use the Agora Cloud Player service to stream videos into your video call or livestream for all other members using the Web UIKit and a NodeJS Backend. Read article](/en/blog/streaming-videos-in-your-livestream-using-the-agora-cloud-player/)

[![Why Ultra-Low Latency Matters for OTT Streaming Performance](/_assets/assets/agoras-website-assets/images/667331869fbfaf38cf122f7c_why-ultra-low-latency-matters-1024x512_noTitle.webp) Business August 31, 2023 Why Ultra-Low Latency Matters for OTT Streaming Performance Explore how ultra-low-latency streaming, with delays under 1 second, revolutionizes user experiences and content consumption in a rapidly evolving digital TV landscape. Read article](/en/blog/why-ultra-low-latency-matters-for-ott-streaming-performance/)

[![Video Course: Building a Complex LiveStream Flutter App](/_assets/assets/agoras-website-assets/images/6673311775e173136f483817_video-course-building-a-complex-livestream-flutter-app-agora.png) Developer October 17, 2022 Video Course: Building a Complex LiveStream Flutter App Build a complex live stream app in Flutter with host controls and ability to broadcast to streaming services using RTMP. Read article](/en/blog/video-course-building-a-complex-livestream-flutter-app/)
