1

I’ve created a very simple AVPlayer within a macOS app.

import Cocoa
import AVKit
import AVFoundation

class ViewController: NSViewController {

@IBOutlet var playerView: AVPlayerView!

override func viewDidLoad() {

    super.viewDidLoad()

    let videoPath = URL(fileURLWithPath: "myPath/myFile.mp4")
    let videoPlayer = AVPlayer(url: videoPath)
    playerView.player = videoPlayer

    }

}

It basically works fine, but the player plays automatically on launch, which it should not. Even when I add playerView.player?.pause() at the end of viewDidLoad, it autoplays.

What am I doing wrong?

ixany
  • 5,433
  • 9
  • 41
  • 65

1 Answers1

1

You should at least put your AVPlayer in the ViewWillAppear() function, and pausing playerView.player would pause your entire view — instead pause videoPlayer:

videoPlayer.pause()

Adding that after playerView.player = videoPlayer should work; your code would then be:

override func viewWillAppear() {
    super.viewWillAppear()

    let videoPath = URL(fileURLWithPath: "myPath/myFile.mp4")
    let videoPlayer = AVPlayer(url: videoPath)
    playerView.player = videoPlayer
    videoPlayer.pause()
}
l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • Thank you so much! Code works fine in `viewWillAppear`, and even without the `.pause()` line the video does not autoplays now. Could you please explain why that makes the difference? – ixany Oct 15 '16 at 22:09
  • 1
    `ViewDIdLoad` loads whether the view has loaded or not, whereas `ViewWillAppear` is called when the view has been fully transitioned onto the screen, meaning it is not "hidden", does not have a hidden ancestor, and is in a window that's ordered in — the default behavior is to do nothing. – l'L'l Oct 15 '16 at 22:13