如何在iOS 12中将本地视频嵌入UIView

时间:2018-10-09 17:27:15

标签: ios swift

我用来在UIView中嵌入本地视频的代码在IOS 12上不起作用。正在播放音频,但出现黑屏。

来自苹果开发者网站:

请勿将AVPlayerViewController子类化。不支持覆盖此类的方法,并且会导致未定义的行为。

该代码在IOS 11上运行良好,知道我需要在代码中进行哪些更改?

谢谢

import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {

    var avPlayer: AVPlayer!

    override func viewDidLoad() {

        super.viewDidLoad()
        let filepath: String? = Bundle.main.path(forResource: "qidong", ofType: "mp4")
        let fileURL = URL.init(fileURLWithPath: filepath!)


        avPlayer = AVPlayer(url: fileURL)


        let avPlayerController = AVPlayerViewController()
        avPlayerController.player = avPlayer
        avPlayerController.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)

        avPlayerController.showsPlaybackControls = false

        avPlayerController.player?.play()
        self.view.addSubview(avPlayerController.view)
    }
}

1 个答案:

答案 0 :(得分:0)

您需要将AVPlayerViewController添加为子视图控制器,如下所示:

import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {

    var avPlayer: AVPlayer!

    override func viewDidLoad() {

        super.viewDidLoad()
        let filepath: String? = Bundle.main.path(forResource: "qidong", ofType: "mp4")
       let fileURL = URL.init(fileURLWithPath: filepath!)


        avPlayer = AVPlayer(url: fileURL)


        let avPlayerController = AVPlayerViewController()
        avPlayerController.player = avPlayer
        avPlayerController.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)

        avPlayerController.showsPlaybackControls = false

        avPlayerController.player?.play()
        self.addChild(avPlayerController)
        self.view.addSubview(avPlayerController.view)
        avPlayerController.didMove(toParent: self)
}

如果您不这样做,那么AVPlayerViewController可能会提前发布。

另一个小问题,但是不使用UIScreen的大小,而是使用视图控制器视图的框架(或者甚至更好地使用自动布局)。