Video in SwiftUI: macOS

One of the great features of SwiftUI is that the same code can run on iOS and macOS. After all, you are just declaring what kind of views you want; the system will translate those to the adequate component according to the system.

So how can we make our Video view compatible with macOS?

On iOS, we were using the UIViewControllerRepresentable protocol to wrap around our UIKit components. For macOS, there are the following equivalent protocols:

Like their iOS counterparts, they allow wrapping around NSView or NSViewController in AppKit.

For our Video component in macOS, because we are wrapping the AVPlayerView, an NSView so we will be using the NSViewRepresentable protocol.

extension Video: NSViewRepresentable {
  public func makeCoordinator() -> VideoCoordinator {
    return VideoCoordinator(video: self)

  public func makeNSView(context: Context) -> AVPlayerView {
    let videoView = AVPlayerView()
    videoView.player = AVPlayer(url: videoURL)

    let videoCoordinator = context.coordinator
    videoCoordinator.player = videoView.player

    return videoView

One of the cool things about his code is because the way we programmed our VideoCoordinator on part 3, it only needs to know about the AVPlayer class so we can reuse it as it is for the macOS version.

We now need to implement the updateNSView method:

public func updateNSView(_ videoView: AVPlayerView, 
                         context: Context) {
  videoView.player?.isMuted = isMuted.wrappedValue

The final touch is to wrap around our implementation with a compiler directive:

#if os(macOS)

extension Video: NSViewRepresentable {


extension Video: UIViewControllerRepresentable {

If you now run our demo app using a macOS application, you should see the following:

As you can see it was quite easy to adapt a component to be used on macOS, I believe this feature of SwiftUI will make it possible to develop a lot more cross-platform applications creating a new boom of development of macOS applications on the long run.

If you want to see the full example have a look at the SVEideoUI repo on Github.

Thanks for reading and see you around.






One response to “Video in SwiftUI: macOS”

  1. Video in SwiftUI: Coordinator – Sérgio Estêvão Avatar

    […] us in part 4 to see how to make this component compatible with […]


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: