title: Playing Streaming Video With AVPlayer
body: <p>How do you play a streaming video with <code>AVPlayer</code>?</p>
  
  <pre><code>import Cocoa
  import AVKit
  
  class StreamViewController: NSViewController {
      var videoPlayer: AVPlayer!
  
      @IBOutlet weak var moviePlayerView: AVPlayerView!
  
      override func viewDidLoad() {
          super.viewDidLoad()        
      }
  
      override func viewWillAppear() {
          super.viewWillAppear()
      }
  
      override func viewDidAppear() {
          super.viewDidAppear()
          openStream()
      }
  
      func openStream() {
          completeOpenStream { (done) -&gt; (Void) in
              if done {
                  print("done!")
              }
          }
      }
  
      func completeOpenStream(completionHandler: @escaping (Bool) -&gt; (Void)) -&gt; Void  {
          DispatchQueue.global().async() {
              let urlString = "http://samples.mplayerhq.hu/V-codecs/h264/interlaced_crop.mp4" // You can open it with QuickTime.
              let url = URL(fileURLWithPath: urlString)
              let avAsset = AVURLAsset(url: url)
              let playerItem = AVPlayerItem(asset: avAsset)
              self.videoPlayer = AVPlayer(playerItem: playerItem)
              self.moviePlayerView.player = self.videoPlayer
              completionHandler(true)
          }
      }
  }
  </code></pre>
  
  <p>If I run it, the app won't crash, but I get a broken link as shown below.</p>
  
  <p><a href="https://i.stack.imgur.com/CeMLU.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/CeMLU.jpg" alt="enter image description here"></a></p>
  
  <p>I have read a few dozen topics here.  One of them says that you have to run it with a background thread.  Another one says that a URL must end with a file type like mp4.  One guy says that you can't with one down vote.  By the way, I write code for both macOS and iOS.  So I leave the topic for both platforms.  Thanks.</p>