在IOS中使用Swift播放MP4

在IOS中使用Swift播放MP4,swift,Swift,这似乎是一项容易的任务,但我再一次发现自己无法解决。这是代码。它返回“找到了视频”,但只显示了一个白色屏幕。救命啊 import Foundation import UIKit import AVFoundation import MediaPlayer import AVKit class SampleView: UIViewController { var sw: CGFloat = 0; var sh: CGFloat = 0; var hw: CGFloat = 0; overri

这似乎是一项容易的任务,但我再一次发现自己无法解决。这是代码。它返回“找到了视频”,但只显示了一个白色屏幕。救命啊

import Foundation
import UIKit
import AVFoundation
import MediaPlayer
import AVKit

 class SampleView: UIViewController {
var sw: CGFloat = 0;
var sh: CGFloat = 0;
var hw: CGFloat = 0;

override func viewDidLoad() {
    super.viewDidLoad()
     if let filePath = Bundle.main.path(forResource: theImage, ofType: "mp4") {
        print("found video")
        let videoURL = URL(string: filePath)
        let player = AVPlayer(url: videoURL!)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
     } else{print("no found video")}

您需要将代码移动到
viewdide
中,因为
viewdideload
视图的层次结构尚未完成,无法显示任何VC

override func viewDidAppear(_ animated:Bool) {
    super.viewDidAppear(animated)
     if let filePath = Bundle.main.path(forResource: theImage, ofType: "mp4") {
        print("found video")
        let videoURL = URL(string: filePath)
        let player = AVPlayer(url: videoURL!)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
     } else{print("no found video")
}

viewDidLoad
现在提供视图控制器还为时过早。