Play a video with AVPlayer in Swift Playground?

I am having trouble playing a video within a swift playground using AVPlayer.

Here’s my code.

  • Bug in UITableView ( deleteSections:withRowAnimation: )?
  • UITesting of Alerts in xCode 7.1
  • Crash on Startup: Xcodebuild's Archive command adds symbolic links to frameworks in place of actual files
  • UIWindow with wrong size when using landscape orientation
  • Xcode 6 how to remove branch in origin
  • iOS: what is the equivalent of an event listener in Objective-C?
  • import UIKit
    import AVFoundation
    var f=CGRectMake(0, 0, 500, 500)
    var url=NSURL(string: "")
    var playerItem = AVPlayerItem(URL: url)
    var v = UIView(frame:f)
    var player=AVPlayer(playerItem: playerItem)
    var playerLayer=AVPlayerLayer(player: player)

    Any suggestions? The code as does nothing at all. My expectation is the ‘v’ variable should be showing the video. It seems to work outside the playground when I am connecting the avplayerlayer to a view from a storyboard.

    3 Solutions Collect From Internet About “Play a video with AVPlayer in Swift Playground?”

    The following should work if you drop it into a playground. Make sure to swap out the path: (Xcode7 GM)

    import UIKit
    import AVFoundation
    import XCPlayground
    var f = CGRectMake(0, 0, 500, 500)
    let path = NSBundle.mainBundle().pathForResource("movie", ofType: "m4v")!
    let url = NSURL(fileURLWithPath: path)
    var playerItem = AVPlayerItem(URL: url)
    var v = UIView(frame: f)
    v.backgroundColor = UIColor.blackColor()
    var player = AVPlayer(playerItem: playerItem)
    var playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = f
    XCPShowView("View", view: v)

    Try adding this at the end to keep the playground running

    import XCPlayground
    XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

    Thanks of @Justin Levi Winter’s answer and I had updated the code for Swift3, tested with Xcode 8 (This video plays in timeline, but not on the Quick Look):

    import AVFoundation
    import PlaygroundSupport
    URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
    let width = 568
    let height = 320
    let container = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
    PlaygroundPage.current.liveView = container
    PlaygroundPage.current.needsIndefiniteExecution = true
    func playVideo(_ url: URL){
        let f=CGRect(x: 0, y: 0, width: width, height: height)
        let playerItem = AVPlayerItem(url: url)
        let player=AVPlayer(playerItem: playerItem)
        let playerLayer=AVPlayerLayer(player: player)
        PlaygroundPage.current.liveView = container