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!
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}"))
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With