Practicing is the best way to acquire knowledge, and you already know we’re big fans of SwiftUI, so this time we will be creating a custom video player for iOS apps in SwiftUI and checking the customization possibilities and limitations. Let’s get started!
As per the official documentation, adding a video player to a SwiftUI app is pretty simple. Import AVKit and add a VideoPlayer view to your own View, with an AVPlayer argument, and we can create one just like this.
Overlays and custom controls
We can then add a second argument to VideoPlayer constructor videoOverlay, which will allow us to add any view on top of the standard player. This view is, however, placed below the standard controls so the system controls will have priority in handling events.
For example, adding a button on top of the player using this video overlay view won't allow us to capture the tap events, as those are the default play/pause event for the player. So any extra buttons (or interactive views) we want to be on top of the video need to be added outside, using a ZStack.
The videoOverlay view however can still be useful for other functions such as displaying text, or capturing events that are unhandled by the system player.
Also something to note is that the overlay will only appear when the video is playing, while any views outside will, of course, be visible always unless we control it ourselves.
Apart from adding custom controls and views to the player, we can interact with it directly from our views. An easy way to start with this is to call the player.play() function programmatically at any point to start the video. We can do this right as the video appears on screen using the onAppear function.
In the first example we created the AVPlayer with just a URL. This can be any file or external resource. But the VideoPlayer view can also receive a queue of videos: to use this we can change the first line in our content view and have the exact same behavior, but now it would be easier to add multiple videos if we want a playlist.
With this we can use the player items to handle the playback, add or remove items to the queue or receive notifications from the player when a video playback ends.
The last topic for this is Picture in Picture, and while it is possible to add PiP to our SwiftUI VideoPlayer, it still cannot be done fully in SwiftUI and also cannot be customized, as it will use the default system style.
Overall we’ve seen that, as with the rest of SwiftUI, the experience using it is pretty straightforward and simple, but it has unsupported features that can be an issue if we really need them for our app. There is always the possibility to use both SwiftUI and UIKit in case we hit a roadblock but that is a limitation we want to avoid as much as possible