Creating a SwiftUI Looping Background Video | by Catalin Patrascu | Mar, 2022

Taking a better have a look at implementing a easy video background in SwiftUI


We’ve got all seen a whole lot of apps with a easy background looping video that astonishes us.

Let’s dive in and see how we are able to do the identical for our app.

In UIKit, we’re doing this by making the most of the AVFoundation framework and UIView. So why not do the identical in SwiftUI, since Apple has a robust mechanism to speak with UIKit?

Additionally, when you’ve got interacted with the same process up to now utilizing UIKit, in all probability you’ve seen there are additionally some explicit states that we have to take into accounts for making a easy video expertise:

  1. pushing/popping the following View or UIViewController
  2. app going into the background
  3. app coming again into the foreground

These explicit mutations could create bizarre unwanted side effects and glitches just like the video stopping and never resuming and even fast-forwarding to a selected level sooner or later.

Our goal is to depart no stone unturned as software program engineers.

Let’s begin with a easy UIView similar as we might have completed again within the UIKit days, making the most of the AVFoundation framework and its elements. Right here’s the code:

Now it’s time to bridge UIKit with SwiftUI through the use of UIViewRepresentable.

And the ultimate piece of the puzzle is to assemble all our code from above inside a SwiftUI View, as proven beneath:

So we’ve got gone from UIKit UIViewRepresentable (the bridge between the 2 worlds) → View (SwiftUI)

Discover how we deal with and management all of the 4 states we talked about earlier than by taking management of the participant and pausing/resuming on completely different state adjustments?

Additionally, AVQueuePlayer must have a state; in any other case, it will likely be invalidated and reset to the beginning of the video on every display screen replace and redraw.

Now, if you wish to use this new type of View anyplace in your code, name it through the use of the next command:

BgdFullScreenVideoView(videoName: "dashboard_video")

For a whole demo and full supply code, every little thing is offered on GitHub.

More Posts