在iOS中,如何以编程方式添加视频视图,然后在使用Swift完成播放后将其删除?

时间:2015-02-15 07:54:55

标签: ios swift video

我想在你登陆主视图之前为应用程序制作一个小介绍视频。代码如下:

import UIKit
import MediaPlayer

class ViewController: UIViewController {

    var moviePlayer: MPMoviePlayerController?
    //var player: MPMoviePlayerController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        playVideo()
        self.view.removeFromSuperview()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func playVideo() {
        let path = NSBundle.mainBundle().pathForResource("paint-me_intro", ofType:"mp4")
        let url = NSURL.fileURLWithPath(path!)
        moviePlayer = MPMoviePlayerController(contentURL: url)
        if let player = moviePlayer {
            player.view.frame = self.view.bounds
            player.controlStyle = .None
            player.prepareToPlay()
            player.scalingMode = .AspectFit
            self.view.addSubview(player.view)
        }
    }
}

我想要它做的就是在视频播放结束后,它需要消失。就这样。在把脸撞到墙上之前,我会非常感激任何帮助。

1 个答案:

答案 0 :(得分:2)

MPMoviePlayerController使用通知进行消息传递,这与许多其他类的委托/协议模式不同。无论如何,回答你的问题。在视图中添加适当通知的观察者确实加载,并指向一个删除视图的函数。

添加观察者

NSNotificationCenter.defaultCenter().addObserver(self, selector: "movieFinished", name:
        MPMoviePlayerPlaybackDidFinishNotification, object: nil)

以及删除它的功能。

func movieFinished() {
    moviePlayer!.view.removeFromSuperview()
    NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
}