使用RxSwift从后台进入前景时,AVPlayer自动播放

时间:2019-02-23 09:15:38

标签: ios swift avplayer rx-swift

我有一个视频,可以在ViewController中播放。
但是当我进入背景然后又回到前景时,视频有时会暂停。
有任何想法让代码添加通知以使用户回到前台并自动播放视频。
谢谢。

extension UIViewController: AVPlayerViewControllerDelegate {

private func playVideo(url: URL, completeHandler: @escaping () -> Void) -> Void {
    let player = AVPlayer(url: url)

    let vc = AVPlayerViewController.init()
    vc.videoGravity = "AVLayerVideoGravityResizeAspectFill"
    vc.showsPlaybackControls = false
    vc.player = player

    // add child view controller
    self.view.addSubview(vc.view)
    self.addChildViewController(vc)
    vc.didMove(toParentViewController: self)
    vc.view.backgroundColor = UIColor.clear

    // constraints
    vc.view.snp.makeConstraints { (make) in
        make.top.equalToSuperview()
        make.bottom.equalToSuperview()
        make.left.equalToSuperview()
        make.right.equalToSuperview()
    }
    // end play
    _ = NotificationCenter.default.rx
    .notification(NSNotification.Name.AVPlayerItemDidPlayToEndTime)
    .takeUntil(self.rx.deallocated)
        .subscribe(onNext: { [weak self] _ in
            for vc in self?.childViewControllers ?? [] {
                if vc is AVPlayerViewController {
                    vc.view.removeFromSuperview()
                    vc.removeFromParentViewController()
                }
            }
            completeHandler()
        })

    vc.player?.play()

}
}

1 个答案:

答案 0 :(得分:0)

好吧,您在UIApplicatonDelegate-https://developer.apple.com/documentation/uikit/uiapplicationdelegate

中有专门用于此目的的回调
  • applicationDidEnterBackground(_:)
  • func applicationWillEnterForeground(UIApplication)

因此,您将不得不从这些回调方法中暂停/恢复视频。