视频播放完毕后,如何使视频消失,以便用户继续使用该应用?

时间:2019-05-04 17:37:51

标签: ios swift avplayer

我写了一些代码在启动后播放视频,但是在播放视频之后,它并没有回到情节提要,它只是停留在此循环中,在此循环中它会回到主板一秒钟然后变黑(可能是视频的结尾)

在调试控制台中,它说“ 2019-05-05 01:32:33.766132 + 0800 app [35989:1028569] [AVKit]当转换全屏视图控制器时,目标视图应该是我们自己的视图!” < / p>

我尝试过一些事情,例如拥有可以感知视频结尾的东西,但是这些都无济于事。

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        playVideo()
    }

    let playerController = AVPlayerViewController()

    private func playVideo() {
        guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        playerController.player = player
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)
        playerController.showsPlaybackControls = false

        present(playerController, animated: true) {
            player.play()
        }
    }

    @objc func playerDidFinishPlaying(note: NSNotification) {
        playerController.dismiss(animated: true, completion: nil)
    }
}

我希望视频播放完后消失,以便用户可以看到该应用的主屏幕。

2 个答案:

答案 0 :(得分:0)

这是问题

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    playVideo()
}

playerVC被关闭,然后出现vc并调用viewDidAppear,以便再次显示玩家,考虑一次bool

var once = true
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if once {
      playVideo()
      once = false
    }
}

或在viewDidLoad中用DispatchAfter显示它

答案 1 :(得分:0)

NotificationCenter.default.addObserver(self, selector: #selector(reachTheEndOfTheVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)

@objc func reachTheEndOfTheVideo(_ notification: Notification) {

}

您可以在avplayer播放结束后为其设置通知,这将使您通过上述方法回叫,您可以停止播放器删除它并更新UI,然后再取消播放器控制器或将其关闭