You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AVPlayer在Collection View Cell中重复打开模态控制器后无法播放显示求助

Hey there, let's tackle this AVPlayer issue you're hitting with your Collection View Cells! I've run into similar headaches before, so here are the most common fixes to get your videos playing reliably every time you present the view controller:

Key Issues & Solutions

1. Fix Cell Reuse & Player Cleanup

Collection View Cells are reused, and if you don't properly reset the AVPlayer/AVPlayerLayer when cells are reused or the view controller is dismissed, leftover instances can block new players from working.

Add Cleanup in Cell's prepareForReuse

This ensures old player states are wiped before the cell is reused:

class VideoCollectionViewCell: UICollectionViewCell {
    var player: AVPlayer?
    var playerLayer: AVPlayerLayer?

    override func prepareForReuse() {
        super.prepareForReuse()
        
        // Stop playback and reset player
        player?.pause()
        player?.replaceCurrentItem(with: nil)
        player = nil
        
        // Remove old player layer from the cell's hierarchy
        playerLayer?.removeFromSuperlayer()
        playerLayer = nil
    }
}

Clean Up When View Controller is Dismissed

Make sure all active players are disposed of when the view controller is closed:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    if isBeingDismissed {
        // Iterate over visible cells to clean up their players
        collectionView.visibleCells.forEach { cell in
            guard let videoCell = cell as? VideoCollectionViewCell else { return }
            videoCell.player?.pause()
            videoCell.player = nil
            videoCell.playerLayer?.removeFromSuperlayer()
            videoCell.playerLayer = nil
        }
    }
}

2. Ensure AVPlayerLayer is Properly Attached to the Cell

Sometimes when reconfiguring cells, the player layer isn't added correctly to the cell's content view, or old layers are left behind. Update your cell configuration code to explicitly handle this:

func configureCell(with videoURL: URL) {
    // Clean up existing player first
    player?.pause()
    playerLayer?.removeFromSuperlayer()
    
    // Create fresh player and item
    let playerItem = AVPlayerItem(url: videoURL)
    player = AVPlayer(playerItem: playerItem)
    
    // Set up and add the player layer
    playerLayer = AVPlayerLayer(player: player)
    playerLayer?.frame = contentView.bounds
    playerLayer?.videoGravity = .resizeAspectFill
    contentView.layer.addSublayer(playerLayer!)
    
    // Start playback (adjust based on your auto-play needs)
    player?.play()
}

3. Fix Memory Leaks from Retain Cycles

If you're using KVO observers or closure-based callbacks with AVPlayer, you might have a retain cycle that keeps old player instances alive, preventing new ones from working properly.

Remove KVO Observers in deinit

deinit {
    player?.removeObserver(self, forKeyPath: "currentItem.status")
    // Remove any other KVO observers you've added
}

Use Weak References in Closures

When using player callbacks, always capture self weakly to avoid cycles:

player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: DispatchQueue.main) { [weak self] time in
    // Handle time updates here – use `self?` to avoid retain cycles
}

4. Rule Out Cache or Network Anomalies

Even if the URL is correct, cached network responses might interfere on subsequent loads. Try forcing a fresh request by ignoring local cache:

let urlRequest = URLRequest(url: videoURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)
let playerItem = AVPlayerItem(url: videoURL)
// Or use AVAsset with the request if you need more control

Start with the cell reuse and cleanup steps first – that's the most common culprit for this exact scenario. If that doesn't fix it, check for memory leaks using Xcode's Instruments tool to spot any retained player instances.

内容的提问来源于stack exchange,提问作者Chetan sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:56:56