Dave
Dave

Reputation: 31

Playing video using swift 2 IOS 9

I'm looking for an example Or source code for playing videos from my application using AVKIT. I couldn't find example of using new version of Swift 2 (IOS 9). Since the MPmovieplayercontroller is deprecated in IOS 9. Any help would be much appreciated.

Upvotes: 3

Views: 6225

Answers (1)

Alex Peda
Alex Peda

Reputation: 4290

You can use AVPlayerViewController class available in iOS 8.0 and later:

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidAppear(animated: Bool) {
         super.viewDidAppear(animated)

        let moviePath = NSBundle.mainBundle().pathForResource("sample_iPod", ofType: "m4v")
        if let path = moviePath {
            let url = NSURL.fileURLWithPath(path)
            let player = AVPlayer(URL: url)
            let playerViewController = AVPlayerViewController()
            playerViewController.player = player
            self.presentViewController(playerViewController, animated: true) {
                if let validPlayer = playerViewController.player {
                    validPlayer.play()
                }
            }
        }

    }
}

EDITED:

That's how you can play the movie without additional screen and custom size:

    let url = NSURL.fileURLWithPath(path)
    let player = AVPlayer(URL: url)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player

    playerViewController.view.frame = CGRectMake(20, 50, 300, 300)
    self.view.addSubview(playerViewController.view)
    self.addChildViewController(playerViewController)

    player.play()

Upvotes: 8

Related Questions