aFella
aFella

Reputation: 205

Implementing UIView in SwiftUI

I am trying to implement a video player in SwiftUI via a UIView following this tutorial: https://medium.com/flawless-app-stories/avplayer-swiftui-b87af6d0553

Unfortunately the video is not displaying, I have AVFoundation imported so I am not sure of the issue. Has anyone found a solution to this?

Here are the classes I created:

class PlayerUIView: UIView {
    private let playerLayer = AVPlayerLayer()
    
    init(frame: CGRect, urlString: String) {
        super.init(frame: frame)
        guard let url = URL(string: urlString) else {
            return
        }
        let player = AVPlayer(url: url)
        player.play()
    
        playerLayer.player = player
        layer.addSublayer(playerLayer)
     }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
     override func layoutSubviews() {
        super.layoutSubviews()
        playerLayer.frame = bounds
     }
}

struct VideoPlayerUIView: UIViewRepresentable {
    
    var frame: CGRect
    var urlString: String
    
    func makeUIView(context: Context) -> some UIView {
        return PlayerUIView(frame: self.frame, urlString: self.urlString)
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
        
    }
}

Here I how I am using the implementation in SwiftUI:

var body: some View {
      Text("Videos")
      VideoPlayerUIView(frame: CGRect(x: 0, y: 0, width: 400, height: 300), urlString: urlString)
}

This was the output (no video) enter image description here

Upvotes: 2

Views: 437

Answers (1)

Coffee and Waffles
Coffee and Waffles

Reputation: 158

You did everything right here.

The only thing that is causing error is how you are process the URL.

Try initialising the player like this instead

     let player = AVPlayer(url: Bundle.main.url(forResource: urlString, withExtension: "mp4")!)

Change the extension according to the format you are using. Remember, here I am force wrapping the optional. So, if you give a wrong urlString or have a video extension other than mp4, the app will crash

Upvotes: 1

Related Questions