在每个Collection View Cell中添加AVPlayerLayer作为子图层?

时间:2018-05-16 00:34:11

标签: ios swift uicollectionview avfoundation

我有一个自定义视图,我嵌入在每个CollectionView单元格中。给定URL时,此视图会检查其是否为照片或视频网址,如果是视频,则会添加AVPlayerLayer并将资产设置为URL。如果是图像,则会添加带有该图像的图像视图。

import UIKit
import Kingfisher
import AVKit
import AVFoundation

class MediaPlayerView: UIView {
    var mediaURL: URL? {
        didSet {
            determineMediaType()
        }
    }
    let videoExtensions = ["mov"]
    var asset: AVURLAsset?
    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }
    var player: AVPlayer?{
        get {
            return playerLayer.player
        }
        set {
            playerLayer.player = newValue
        }
    }
    override static var layerClass: AnyClass {
        return AVPlayerLayer.self
    }
    static let assetKeysRequiredToPlay = [
        "playable",
        "hasProtectedContent"
    ]

    private var playerItem: AVPlayerItem? = nil

    override init (frame : CGRect) {
        super.init(frame : frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //determineMediaType()
    }

    func determineMediaType() {
        let url = self.mediaURL
        let pathExtention = url?.pathExtension
        print(url)
        print(pathExtention)
        if videoExtensions.contains(pathExtention!) {
            print("Movie URL: \(String(describing: url))")
            setupVideo(url: url!)
        } else {
            print("Image URL: \(String(describing: url))")
            setupImage(url: url!)
        }
    }

    func setupVideo(url: URL) {
        self.layer.addSublayer(playerLayer)
        asset = AVURLAsset(url: url, options: nil)
    }

    func setupImage(url: URL) {
        let imageView = UIImageView()
        imageView.frame = self.bounds
        imageView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        self.addSubview(imageView)
        imageView.kf.setImage(with: url)
    }

}

现在,当创建此视图时,它将终止此异常:

Terminating app due to uncaught exception 'CALayerInvalid', reason: 'layer <AVPlayerLayer: 0x60c000a26760> is a part of cycle 

我认为这是一个问题,因为我将setupVideo函数中的playerLayer添加到self,它已经覆盖了LayerClass,总是给AVPlayerLayer.self。 AKA将播放器层添加为自身的子视图。但我不知道如何避免这种情况?

0 个答案:

没有答案