Creating a SwiftUI Looping Background Video
Taking a closer look at implementing a smooth video background in SwiftUI
We have all seen a lot of apps with a smooth background looping video that astonishes us.
Let’s dive in and see how we can do the same for our app.
In UIKit
, we are doing this by taking advantage of the AVFoundation
framework and UIView
. So why not do the same in SwiftUI
, since Apple has a powerful mechanism to communicate with UIKit
?
Also, if you have interacted with a similar task in the past using UIKit
, probably you have noticed there are also some particular states that we need to take into consideration for creating a smooth video experience:
- pushing/popping the next
View
orUIViewController
- app going into the background
- app coming back into the foreground
These particular mutations may create weird side effects and glitches like the video stopping and not resuming or even fast-forwarding to a specific point in the future.
Our aim is to leave no stone unturned as software engineers.
Let’s start with a simple UIView
same as we would have done back in the UIKit
days, taking advantage of the AVFoundation
framework and its components. Here’s the code:
Now it’s time to bridge UIKit
with SwiftUI
by using UIViewRepresentable
.
And the final piece of the puzzle is to assemble all our code from above inside a SwiftUI
View
, as shown below:
So we have gone from UIKit
→ UIViewRepresentable
(the bridge between the two worlds) → View
(SwiftUI
)
Notice how we handle and control all the four states we mentioned before by taking control of the player and pausing/resuming on different state changes?
Also, AVQueuePlayer
needs to have a state; otherwise, it will be invalidated and reset to the start of the video on each screen update and redraw.
Now, if you want to use this new kind of View
anywhere in your code, call it by using the following command:
BgdFullScreenVideoView(videoName: "dashboard_video")
For a complete demo and full source code, everything is available on GitHub.