在IOS中使用Swift播放MP4

时间:2018-04-16 23:28:34

标签: 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;

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")}

1 个答案:

答案 0 :(得分:0)

您需要将代码移至viewDidAppear,因为viewDidLoad视图的层次结构尚未完成以呈现任何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")
}