设置UISlider的最小值和最大值时发生错误

时间:2019-05-22 17:35:19

标签: ios swift uislider

我正在从我的应用程序中播放用户库中的视频。我在ViewDidLoad()中使用此方法来获取视频:

fileprivate let imageManager = PHImageManager()
fileprivate var playerLayer: AVPlayerLayer?
fileprivate var player:AVPlayer?
fileprivate var videoView:UIView?

imageManager.requestPlayerItem(forVideo: videoAsset, options: options, resultHandler: { playerItem, info in
            DispatchQueue.main.sync {
                guard self.playerLayer == nil else { return }

                self.player = AVPlayer(playerItem: playerItem)
                self.playerLayer = AVPlayerLayer(player: self.player)

                self.videoView = UIView(frame: self.view.frame)
                self.videoView?.contentMode = .scaleAspectFit
                self.playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
                self.playerLayer?.frame = self.videoView!.layer.bounds
                self.videoView!.layer.addSublayer(self.playerLayer!)
                self.photoScrollView.addSubview(self.videoView!)
                self.addObserversForVideo()
            }
        })

在addObserversForVideo()内部,我设置了不同的观察者以更新控制视频的滑块,并设置其最小值和最大值:

        guard let currentPlayer = player else {return}
        guard let currentItem = currentPlayer.currentItem else {return}

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

        let interval = CMTime(seconds: 0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
        _ = playerLayer?.player?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { [weak self] (time) in

            self?.videoSlider.maximumValue = Float(currentItem.duration.seconds)
            self?.videoSlider.minimumValue = 0.0
            self?.videoSlider.value = Float(currentItem.currentTime().seconds)
            self?.videoElapsedTimeLabel.text = self?.getStringFromCMTime(time: currentItem.currentTime())

            let remainingTime = currentItem.duration - currentItem.currentTime()
            self?.videoRemainingTimeLabel.text = self?.getStringFromCMTime(time: remainingTime)

        })

现在,问题是我有时出现此错误,导致我的应用崩溃:

  

“ NSInternalInconsistencyException”,原因:“尝试设置一个   滑块的minimumValue(0.000000)大于maximumValue   (nan)'

我不明白为什么会这样,因为我在一开始使用保护声明检查currentItem是否为非零,并且还在最大值之后设置最小值。如果有人可以帮助我,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

由于@TonyNguyen,我可以在一行中解决此问题:

    guard currentItem.status.rawValue == AVPlayerItem.Status.readyToPlay.rawValue else {return}

答案 1 :(得分:0)

您需要防止另外两件事:

  • currentPlayer.currentItem.status == .readyToPlay
  • currentPlayer.currentItem.duration >= CMTime.zero