skip to Main Content

I have this json and I have to play a videoenter image description here

What is the best way to play video and validate or check if user watched whole video?
Video could be (Tiktok – Vimeo – Dayli Motion) video but no Youtube Video

I tried to use AVPlayer but it doesn’t work :

    let videoURL = NSURL(string: "https://vimeo.com/601097657")
    let player = AVPlayer(url: videoURL! as URL)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
    }

I think the possible solution it could be a webView but I’m not sure if its possible to validate if user watched whole video

2

Answers


  1. This is working for me.

    class Player: AVPlayerViewController {
    
    init(url: URL) {
        super.init(nibName: nil, bundle: nil)
        player = AVPlayer(url: url)
        player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: DispatchQueue.main, using: { time in
            if self.player?.currentItem?.status == .readyToPlay {
                let currenTime = CMTimeGetSeconds((self.player?.currentTime())!)
                let secs = Int(currenTime)
                print(NSString(format: "%02d:%02d", secs/60, secs%60) as String)
            }
        })
    }
    

    This will print out how much of the video they have watched in seconds, which you could then check if this is equal to the total amount of time the video is.

    Obviously you would have to implement methods to check if they have skipped part of the video or not, but that’s for another question.

    Check out more info Time watched. and Total Video Time

    Login or Signup to reply.
  2. AVPlayer sends notifications on occasions like that.

    Simply subscribe to notifications you need. In your case you need

    NSNotification.Name.AVPlayerItemDidPlayToEndTime

    implementing this would look something like this:

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(itemDidPlayToEnd),
                                           name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                           object: nil)
    

    And implement a selector for handling notification:

    @objc private func itemDidPlayToEnd() { 
        // do smth 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search