NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to play movies with VideoPlayer

Paul Hudson    @twostraws   

Updated for Xcode 12.0

New in iOS 14

SwiftUI’s VideoPlayer view lets us playback movies from any URL, local or remote. It comes from the AVKit framework, so you should make sure and add import AVKit before trying it out.

Warning: At this time VideoPlayer works great on device, but seems to struggle in the simulator.

As an example, if you had video.mp4 in your app bundle and wanted to play it back, you’d use this:

VideoPlayer(player: AVPlayer(url:  Bundle.main.url(forResource: "video", withExtension: "mp4")!))

Reminder: You need to add import AVKit to your Swift file to use this.

And if you want to play a remote video, use its remote URL instead:

VideoPlayer(player: AVPlayer(url:  URL(string: "https://bit.ly/swswift")!))

If you want, you can provide a second parameter to the VideoPlayer initializer that adds content to be drawn over the video. This will be drawn below the system video controls, but can respond to any events that aren’t caught by those controls.

For example, this places the text “Watermark” at the very top of the video area:

VideoPlayer(player: AVPlayer(url:  URL(string: "https://bit.ly/swswift")!)) {
    VStack {
        Text("Watermark")
            .font(.caption)
            .foregroundColor(.white)
            .background(Color.black.opacity(0.7))
            .clipShape(Capsule())
        Spacer()
    }
}
Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.4/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.