Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何判断AVPlayer何时播放了3秒钟_Ios_Swift_Tableview_Avplayer - Fatal编程技术网

Ios 如何判断AVPlayer何时播放了3秒钟

Ios 如何判断AVPlayer何时播放了3秒钟,ios,swift,tableview,avplayer,Ios,Swift,Tableview,Avplayer,我有一个包含视频的应用程序,当单元格可见时,该应用程序会在UIImageView中的UITableView中自动播放视频,我要做的就是让应用程序知道视频何时播放了三秒。我写了这段代码 class PostCell: UITableViewCell { var player: AVPlayer? var playerLayer: AVPlayerLayer? var post: Post? { didSet { updateView()

我有一个包含视频的应用程序,当单元格可见时,该应用程序会在
UIImageView
中的
UITableView
中自动播放视频,我要做的就是让应用程序知道视频何时播放了三秒。我写了这段代码

    class PostCell: UITableViewCell {

    var player: AVPlayer?
    var playerLayer: AVPlayerLayer?

    var post: Post? {
    didSet {
        updateView()
    }
}

    func updateView() {

    self.viewcount()

    if let videoUrlString = post?.videoUrl, let videoUrl = URL(string: videoUrlString) {
        player = AVPlayer(url: videoUrl)
        playerLayer = AVPlayerLayer(player: player)
        playerLayer?.frame = postImageView.frame
        playerLayer?.frame.size.width = postImageView.frame.size.width
        playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        self.contentView.layer.addSublayer(playerLayer!)

        player?.play()
    }
      func viewcount() {
    if let currentitem = player?.currentItem {
        if currentitem.currentTime() == CMTimeMake(3, 1) {
            print ("VIDEO PLAYED FOR THREE SECONDS")
        }
      }
   }
}

但一旦视频开始播放,它就不会打印出我的信息。我在网上搜索了帮助,但找不到关于这个主题的任何东西。所以,有人能帮我解决这个问题,告诉我我做错了什么吗?

请在播放器开始播放后尝试调用视图计数

func updateView() {

    /// Not here Because at this time player current item is not initiated yet
    /// if you use Breakpoints in viewCount code you will see it won't enter
    /// in if condition created
    self.viewcount() /// Comment this line
    if let videoUrlString = post?.videoUrl, let videoUrl = URL(string: videoUrlString) {
        player = AVPlayer(url: videoUrl)
        playerLayer = AVPlayerLayer(player: player)
        playerLayer?.frame = postImageView.frame
        playerLayer?.frame.size.width = postImageView.frame.size.width
        playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        self.contentView.layer.addSublayer(playerLayer!)
        /// Player is initiated with a item to play
        player?.play()
        /// Call current time here
        /// Now it will Enter in if Condition 
        /// Also try using else statement so you know Do control enter in if or in Else
        self.viewcount()
    }


func viewcount()
    {
        if let currentitem = player?.currentItem
        {
            ///Yes Player have a item whose time can be Detected
            if currentitem.currentTime() == CMTimeMake(3, 1)
            {
                print ("VIDEO PLAYED FOR THREE SECONDS")
            }
        }
        else
        {
            /// Check do Control reach here in case 1 When you are calling before player.play()
        }
    }

您正在搜索玩家的观察者,这里是您如何检查和跟踪AVPlayer的当前位置

下面是将观察者添加到单元格的函数

private func addObserversForVideoPlayer(cell:CustomCell) {

   let observer =  cell.player?.addPeriodicTimeObserver(forInterval: CMTime.init(seconds: 1, preferredTimescale: 1), queue: .main, using: {[weak self,weak cell] (time) in
        guard let cell = cell else {return}

        if cell.player?.currentItem?.status == .readyToPlay {
            // print("Inside Will DISPLAY\(cell.video.currentTime)")

            let timeDuration : Float64 = CMTimeGetSeconds((cell.player?.currentItem?.asset.duration)!)
            cell.lblDuration.text = self?.getDurationFromTime(time: timeDuration)

            let currentTime : Float64 = CMTimeGetSeconds((cell.player?.currentTime())!)
            cell.lblStart.text = self?.getDurationFromTime(time: currentTime)
            cell.slider.maximumValue = Float(timeDuration.rounded())
            cell.slider.value = Float(currentTime.rounded())

        }
    })
    NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: cell.player?.currentItem, queue: .main, using: {[weak cell,weak self]  (notification) in

        if cell?.player != nil {
            cell?.player?.seek(to: kCMTimeZero)
            cell?.player?.play()
        }
    })
}
这样
addPeriodicTimeObserver
将在播放器开始播放时通知您

NSNotification.Name.AVPlayerItemDidPlayToEndTime
将在AVPlayer停止时通知您

注1:如果在添加
AVPlayerItemDidPlayToEndTime
时,您的
cell.player?.currentItem
为nil,则会导致出现错误,如果出现此错误,请参阅。您不需要它,不要添加它:)

注2:您应该保留
观察者
,以便在一段时间后可以删除它,这样就不会对内存造成额外负载

希望它有帮助

特别是:尝试在player.Play()之后调用self.viewcount(),就像在self.viewcount()中一样。您正在检查player当前时间,而此时它没有播放任何内容