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

问题描述 投票:0回答:1

我有一个视频并在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()

}
}
ios swift avplayer rx-swift
1个回答
0
投票

好吧,你在UIApplicatonDelegate - https://developer.apple.com/documentation/uikit/uiapplicationdelegate中完全为此目的回调

  • applicationDidEnterBackground(_:)
  • func applicationWillEnterForeground(UIApplication)

因此,您必须暂停/恢复这些回调方法中的视频。

© www.soinside.com 2019 - 2024. All rights reserved.