Search code examples
iosswiftmp4mpmovieplayer

How to recognize a tap gesture while using an MPMoviePlayerController


I am attempting to recognize a tap gesture while a video is playing so that I can dismiss it similarly to how snapchat does this, however, it says that MPMoviePlayerControllers have no members to add touch gestures, is this true or am I using the incorrect method?

var MP4 : NSData?
var MarkerLong : CLLocationDegrees?
var MarkerLat : CLLocationDegrees?
var Url : String?
var videoPlayer : MPMoviePlayerController!

private var firstAppear = true

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    if firstAppear {
        do {
            try playVideo()
            firstAppear = false
        } catch AppError.InvalidResource(let name, let type) {
            debugPrint("Could not find resource \(name).\(type)")
        } catch {
            debugPrint("Generic error")
        }

    }
}

private func playVideo() throws {

    self.videoPlayer = MPMoviePlayerController()
    self.videoPlayer.repeatMode = MPMovieRepeatMode.None
    self.videoPlayer.contentURL = NSURL(string: Url!)
    self.videoPlayer.controlStyle = MPMovieControlStyle.None
    self.view.addSubview(self.videoPlayer.view)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayVideoViewController.videoPlayBackDidFinish(_:)), name: MPMoviePlayerPlaybackDidFinishNotification, object: self.videoPlayer)
    self.videoPlayer.view.frame.size = CGSizeMake(640, 1136)
    self.videoPlayer.view.center = self.view.center
    self.videoPlayer.play()
    let gesture = UITapGestureRecognizer(target: self, action: "someAction:")
    self.videoPlayer.addGestureRecognizer(gesture)

}

Solution

  • I would reccomend using AVPlayerViewController, but make sure not to subclass it, as Apple states not to.

    1) MPMoviePlayer is deprecated (Don't use this code anymore)

    2) AVPlayerViewController has a much more intricate set of code to allow more customization.

    If you really want to customize something, you can subclass AVPlayer and make your own customized view where the video will be played, but you will have to add your own pause/start, etc...