2

So, im having a lot of trouble playing a video inside a UIView in my Swift application. To start with, that might not even be the right way to do it. What I want to achieve is playing a video inside a rectangle at the top of the ViewController, eg not in fullscreen. But no matter what i try, as soon as I hit the play button it toggles fullscreen mode. How would I go about doing this? Thanks a lot guys

This is the code im using to play the video

@IBAction func feedConnect(_ sender: Any) {
    let url = feedUrl.text
    writeToFile(fileName: "connections", stringToWrite: url!)
    let movieURL:NSURL? = NSURL(string: url!)

    if let url = movieURL {
        self.avPlayer = AVPlayer(url: url as URL)
        self.avPlayerViewController.player = self.avPlayer
        self.avPlayerViewController.entersFullScreenWhenPlaybackBegins = false

    }
    self.present(self.avPlayerViewController, animated: true, completion: {() -> Void in self.avPlayerViewController.player?.play()})

}

I want do play the video inside the gray rectangle like this: 1

hardik parmar
  • 853
  • 8
  • 15
lunarkakka
  • 55
  • 2
  • 7

1 Answers1

0

Rather than using the AVPlayerViewController, you can use an AVPlayerLayer. Give this the frame that it needs, then add it as a sublayer to your view's layer.

For example here I have a UIView called playerArea which is your grey rectangle:

let playerLayer = AVPlayerLayer(player: player) playerLayer.frame = playerArea.frame playerArea.layer.addSublayer(playerLayer)

Steven Gurr
  • 101
  • 3
  • How would you go about doing this? – lunarkakka Oct 11 '18 at 10:52
  • I've edited my post now to include a small code sample. – Steven Gurr Oct 11 '18 at 10:57
  • How do you play the video inside the view after doing this? when i write player.play() it play the audio but it doesnt display the video inside the view – lunarkakka Oct 11 '18 at 11:25
  • Is the view definitely visible on screen? For me just calling play was enough. If you're getting the audio it suggests it is playing but you just can't see it. – Steven Gurr Oct 11 '18 at 11:26
  • If you're setting it to the frame of your grey box, make sure the grey box has rendered first. If you do this in viewDidLoad it might not be laid out yet. Try deferring it to viewDidAppear or some other later event. – Steven Gurr Oct 11 '18 at 11:27
  • Yes, i think so. Ill update the question with a picture of the storyboard and the code – lunarkakka Oct 11 '18 at 11:30