预加载视频并缓存它们 - Swift

发布于 2025-02-07 18:28:55 字数 1082 浏览 1 评论 0原文

我有CollectionView,每个单元格都显示一个视频。

当一个单元格被挖掘时,我会提供播放视频的ViewController。

在ViewController中执行此操作的代码如下:

fileprivate func configureVideo(with moment : Moment){
    guard let urlString = moment.videoUrl else { return }
    guard let videoUrl = URL(string: urlString) else { return }
    self.player = AVPlayer(url: videoUrl)
    
    dispatchGroup.enter()
    
    self.player!.addObserver(self, forKeyPath: #keyPath(player.currentItem.isPlaybackLikelyToKeepUp),
                             options: .new, context: &playbackLikelyToKeepUpContext)
    
    NotificationCenter.default.addObserver(self, selector: #selector(videoReachedEnd), name: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
    
    self.playerLayer = AVPlayerLayer(player: player)
    self.view.layer.insertSublayer(playerLayer!, at: 0)
    self.playerLayer?.frame = self.view.bounds
    self.player?.play()
}

在显示控制器时正在加载视频的事实使视频加载过程比我想要的更长。

我希望在我浏览CollectionView的单元格之前已经加载了视频,以便当我点击单元格并显示控制器时,视频已经准备好播放。

但是我不知道这是正确的方法。 如果您有任何建议,我愿意听。

I have collectionView and each cell has a video displayed.

When a cell is tapped I present a ViewController that plays the video.

The code that does this in the ViewController is as follows:

fileprivate func configureVideo(with moment : Moment){
    guard let urlString = moment.videoUrl else { return }
    guard let videoUrl = URL(string: urlString) else { return }
    self.player = AVPlayer(url: videoUrl)
    
    dispatchGroup.enter()
    
    self.player!.addObserver(self, forKeyPath: #keyPath(player.currentItem.isPlaybackLikelyToKeepUp),
                             options: .new, context: &playbackLikelyToKeepUpContext)
    
    NotificationCenter.default.addObserver(self, selector: #selector(videoReachedEnd), name: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
    
    self.playerLayer = AVPlayerLayer(player: player)
    self.view.layer.insertSublayer(playerLayer!, at: 0)
    self.playerLayer?.frame = self.view.bounds
    self.player?.play()
}

The fact that the video is being loaded when the controller is presented makes the process of video loading longer than I would like it to.

I would like that the videos are being loaded before, when I am scrolling through the cells of the collectionView, so that when I tap on a cell and the controller is presented, the video is already ready to play.

But I don't know what would be the right approach for it.
If you have any suggestions I am willing to listen.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文