Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In swift, how to detect touch while playing video in AVPlayerViewController

I have programmatically added an AVPlayerViewController to a UIViewController. I am able to receive the notification when the player is finished playing (playerDidFinishPlaying). I would also like to know if a user has touched the screen while the video is playing and I have not found any related notifications.

like image 783
Bruce Avatar asked Oct 05 '16 23:10

Bruce


People also ask

How do I know when AVPlayer video is playing?

If you want to check the status of a played video - one of the best solutions is to add an observer to the AVPlayer item . The AVPlayerViewController doesn't notify about the ending of a video. This is why you need to check it by yourself. You should add the NotificationCenter observer to your playVideo() method.

How do I know if AV player is playing Swift?

Currently with swift 5 the easiest way to check if the player is playing or paused is to check the . timeControlStatus variable.


1 Answers

The solution is to create a Base class of AVPlayerViewController and override touches​Began(_:​with:​) method:

Swift 2:

Custom Base Class:

class CustomAVPlayerViewController: AVPlayerViewController {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("touchesBegan")
    }
}

ViewController:

let videoURL = NSURL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(URL: videoURL!)
let playerViewController = CustomAVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
    playerViewController.player!.play()
}

Swift 3:

Custom Base Class:

class CustomAVPlayerViewController: AVPlayerViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchesBegan")
    }
}

View Controller:

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerViewController = CustomAVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
    playerViewController.player!.play()
}

Don't forget to import AVKit and import AVFoundation.

Each time you tap on the playerViewController, "touchesBegan" will be printed.

like image 199
Ahmad F Avatar answered Sep 21 '22 01:09

Ahmad F