Home > Software engineering >  How do I add a local video ? SWIFTUI
How do I add a local video ? SWIFTUI

Time:10-20

I have the code and I need to save its functions, but the video does not need to be downloaded from the Internet, I need to show the downloaded video from my project. SWIFTUI

I will be grateful for any your help

This is how my code looks now:

class UIVideoPlayer: UIView {
    
    var playerLayer = AVPlayerLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        guard let url = URL(string: "https://video.mp4") else { return }

        let player = AVPlayer(url: url)
        player.isMuted = true
        player.play()
      
        playerLayer.player = player
        playerLayer.videoGravity = AVLayerVideoGravity(rawValue: AVLayerVideoGravity.resizeAspectFill.rawValue)
        
        layer.addSublayer(playerLayer)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        playerLayer.frame = bounds
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

struct Players: UIViewRepresentable {

    func makeUIView(context: Context) -> UIVideoPlayer {
        return UIVideoPlayer()
    }

    func updateUIView(_ uiView: UIVideoPlayer, context: Context) {
        
    }
 }

CodePudding user response:

Replace this line: guard let url = URL(string: "https://video.mp4") else { return }

With this:

guard let url = guard let url = Bundle.main.url(forResource: "video", withExtension: ".mp4") { return }

(Assuming your file is named video.mp4 and is added to your project and target.

  • Related