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.
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
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:
- pushing/popping the following
- app going into the background
- 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
SwiftUI through the use of
And the ultimate piece of the puzzle is to assemble all our code from above inside a
View, as proven beneath:
So we’ve got gone from
UIViewRepresentable (the bridge between the 2 worlds) →
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?
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:
For a whole demo and full supply code, every little thing is offered on GitHub.