Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding videos in a SwiftUI view

My main goal is to embed a GIF/MP4 file in a view in a HStack/VStack using SwiftUI. I understand the code needs to conform to the 'Representable' protocols. My first attempt at doing this is below:

import SwiftUI
import AVKit

struct GIF : UIViewControllerRepresentable {

    let url_name: String

    func makeUIViewController(context: UIViewControllerRepresentableContext<GIF>) -> AVPlayerViewController {
        return AVPlayerViewController()
    }

    func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<GIF>) {
        let url = URL(string: url_name)!
        let player = AVPlayer(url: url)
        let vc = AVPlayerViewController()
        vc.player = player
//PROBLEM
        self.present(vc, animated: true){
            vc.player?.play()
        }
    }
}

The problem is that I don't think 'self' makes any sense here and we need to refer to a view. How would we do this? We can't just create a view in a story board as I want to integrate the view controller with SwiftUI.

Any help would be appreciated.

P.S. This is my first iOS app so if I'm missing something very obvious here please try to be kind!

like image 360
Vedant Avatar asked Jul 08 '19 19:07

Vedant


1 Answers

it's easy to wrap old AVPlayerViewController

import AVKit
import SwiftUI

struct AVPlayerView: UIViewControllerRepresentable {
@Binding var videoURL: URL?

private var player: AVPlayer? {
    guard let url = videoURL else {
        return nil
    }
    return AVPlayer(url: url)
}

func updateUIViewController(_ playerController: AVPlayerViewController, context: Context) {
    playerController.player = player
    playerController.player?.play()
}

func makeUIViewController(context: Context) -> AVPlayerViewController {
    AVPlayerViewController()
}
}

but if ur target is equal or higher than 14 u can use VideoPlayer component from swiftui without any wrappers

import SwiftUI
import AVKit

struct UrView: View {
    var body:  some  View {
         VideoPlayer(
             player: AVPlayer(url: URL(string: "{ur url}"))
         )
    }
}
like image 133
alexis Avatar answered Sep 22 '22 17:09

alexis