gpt4 book ai didi

ios - 在 tableview 中平滑加载视频

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:12:27 24 4
gpt4 key购买 nike

我一直在尝试使用我放入 TableView Cell 中的 AVPlayer 将一些视频添加到我的 tableView 中。

但是在加载视频时 UI 卡住。

这是我在 indexpath 的 cellforRow。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCel {


var tableCell : UITableViewCell? = nil

if (tableCell == nil){

tableCell = tableView.dequeueReusableCell(withIdentifier: "cell")
}

let view = tableCell?.viewWithTag(9999)
tableCell?.tag = indexPath.row


DispatchQueue.main.async {
if (tableCell?.tag == indexPath.row){
let player = self.cache.object(forKey: indexPath.row as AnyObject) as! AVPlayer
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = (view?.bounds)!
view?.layer.addSublayer(playerLayer)
player.play()

}

// tableView.reloadData()
}

return tableCell!
}

这就是我将视频添加到缓存的方式。

    for i in 0...10{

var videoURL : URL? = nil

if (i%2 == 0){

videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
}else{

videoURL = URL(string: "http://techslides.com/demos/sample-videos/small.mp4")

}
let player = AVPlayer(url: videoURL!)

arr?.append(player)

self.cache.setObject(player, forKey: i as AnyObject)
print("count = \(arr?.count)")
}

解决此问题的最佳方法是什么?

最佳答案

谢天谢地,你很幸运。 iOS 针对这些类型的问题进行了优化。 Apple 工程师竭尽全力提供 API 来帮助您实现流畅的滚动同时加载您的内容。

Note: Solving this issue requires offloading tasks to different threads on the CPU. It can get complicated, and there's a lot to learn about it. I strongly recommend you read Apple's documentation.

首先,知道 cellForRowAtIndexPath: 方法应该通常在主线程上调用您的数据源。这意味着您必须调用 DispatchQueue.main.async 在这种情况下使用不当。

相反,您需要做的是将您的 AVPlayer 缓存卸载到一个单独的后台线程,然后返回到主线程以更新单元格的层内容。此外,您不应该在 cellForRowAtIndexPath: 中这样做。您可能需要子类化 UITableViewCell 并在其中编写您自己的加载序列 - 这样,您可以快速初始化您的自定义单元格,将其返回给 cellForRowAtIndexPath:(然后可以愉快地继续),并继续从单元格子类中加载内容和更新。

要在后台线程中设置您的 AVPlayer,请执行以下操作:

DispatchQueue.global(qos: .background).async {
// Background thread
// Do your AVPlayer work here

// When you need to update the UI, switch back out to the main thread
DispatchQueue.main.async {
// Main thread
// Do your UI updates here
}
}

您可能想查看在创建后台线程时传入的服务质量值。 userInitiated QOS 对于这种特定情况可能更好,因为视频是作为用户启动操作的结果加载的。

至于视频的实际缓存。我不太熟悉 AVPlayerAVPlayerItem,但根据我的理解,您可以提供更多元数据(即持续时间、轨道等) AVPlayer 在尝试在图层中渲染视频之前,速度越快(参见相关的 StackOverflow Question )。

此外,您可能想要查看 iOS 10 中新引入的 API,所有这些 API 都可以在表格 View 中预取单元格。如果您利用预取优化,您可能会在后台加载 AVPlayer 所需的一切,并且在单元格被请求显示在 cellForRowAtIndexPath: 之前.

无论如何,希望您能从那里着手解决问题。一定要花时间阅读有关 AVKitGCDUITableView(特别是新的预取 API)的文档。

关于ios - 在 tableview 中平滑加载视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43118501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com