我将本地视频加载到新的视图控制器中,但点击完成后,它消失了,并立即再次弹出。我不知道是否有办法跟踪通知或什么。

这是我的代码:

import UIKit
import AVKit
import AVFoundation

class VideoController1: UIViewController {

    var playerViewController = AVPlayerViewController()
    var playerView = AVPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
        playerView = AVPlayer(url: fileURL as URL)
        playerViewController.player = playerView
        self.present(playerViewController, animated: true){
            self.playerViewController.player?.play()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

最佳答案

你把你的代码

let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
    playerView = AVPlayer(url: fileURL as URL)
    playerViewController.player = playerView
    self.present(playerViewController, animated: true){
        self.playerViewController.player?.play()
    }


ViewController的ViewDidAppear内部。

当视图再次出现在屏幕上时,会发生ViewDidAppear()。因此,这意味着,当关闭AVPlayer时,它将返回到该视图,并且将再次显示AVPlayer。

您有2个选项:

创建一个UIButton并对该按钮进行操作

var button = UIButton(frame: CGRect(0, self.view.frame.height*0.9, self.view.frame.width, self.view.frame.height*0.1))
button.addTarget(self, #selector(VideoController1.playController), nil)
self.view.addSubview(button)

let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")

func playController() {
    playerView = AVPlayer(url: fileURL as URL)
    playerViewController.player = playerView
    self.present(playerViewController, animated: true){
        self.playerViewController.player?.play()
    }
}


- 要么 -

如果您希望控制器仅在用户第一次看到该视图时播放,就是这样,那么您可以

var played = false

func viewDidAppear() {
    if(!played) {
        let fileURL = NSURL(fileURLWithPath: "/Users/jamesjarrett/Desktop/NIMS/NIMS/NIMS/Vid2.mp4")
        playerView = AVPlayer(url: fileURL as URL)
        playerViewController.player = playerView
        self.present(playerViewController, animated: true){
            played = true
            self.playerViewController.player?.play()
        }
    }
}


不要在上面的代码中引用我,只需快速输入一下即可大致了解您。

09-08 01:52