Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing video using swift 2 IOS 9

Tags:

ios9

video

swift2

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.

like image 794
Dave Avatar asked Dec 05 '25 11:12

Dave


1 Answers

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()
like image 71
Alex Peda Avatar answered Dec 08 '25 02:12

Alex Peda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!