Play a Video from URL in SwiftUI


In this tutorial, I will show you how you can play a video from an URL in SwiftUI in a simple way. We are going to use AVKit framework to achieve this task.

AVKit already comes with Xcode. All you need to do is just to import this framework and then you are ready to follow the upcoming tutorial.

Let’s import AVKit:

import AVKit

After that, create a state variable for the player. Assign the value of AVPlayer() object in this state variable as you can see below:

@State var player = AVPlayer()

Now let’s create a string-type Swift variable to store our video link or URL:

var vidURL: String = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"

Next, use the VideoPlayer view and use the onAppear() action to add our video URL. Our video URL will be a direct link to the video file. It should be SSL secure which means, the URL should have HTTPS protocol.

Below is the given how our view looks like:

    var body: some View {
            
                VideoPlayer(player: player)
                    .onAppear() {
                            player = AVPlayer(url: URL(string: vidURL)!)
                    }
        
    }

Complete working code

Below is the complete Swift program of the view file that can play a video from the internet by using the video file URL:

import SwiftUI
import AVKit

struct ContentView: View {
    
    @State var player = AVPlayer()
    
    var vidURL: String = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
   
    var body: some View {
            
                VideoPlayer(player: player)
                    .onAppear() {
                            player = AVPlayer(url: URL(string: vidURL)!)
                    }
        
    }

}

Now if we run it on the device, it will show a video player like you can see below:

iOS video player using AVKit

That’s it. I hope this tutorial will help you in your iOS development project.

Note: It will not play the YouTube video by providing a YouTube video link. You have to provide the direct video file link of the video.