我想在我的应用程序的背景中有一个视频,但是我已经通过让我的所有类继承自这个类
来做到这一点class MyClass: UIViewController {
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
let theURL = Bundle.main.url(forResource:"video", withExtension: "mp4")
avPlayer = AVPlayer(url: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = .none
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = .clear
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
}
func playerItemDidReachEnd(notification: Notification) {
let p: AVPlayerItem = notification.object as! AVPlayerItem
p.seek(to: kCMTimeZero)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
avPlayer.play()
paused = false
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
avPlayer.pause()
paused = true
}
问题在于,当我从视图控制器更改时,视频重新开始,我不想要这个,我希望视频在最后一个视图控制器中继续,我的解决方案将实例化一个视频和我所有视图控制器上的访问权限购买我该怎么做?还是有另一种解决方案?
答案 0 :(得分:1)
您可以使用Singleton实现这一目标。
以下是示例:
final class VideoPlayerManager {
static let shared = VideoPlayerManager()
private init() { }
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
}
致电viewDidLoad
:
VideoPlayerManager.shared.avPlayer.play()
答案 1 :(得分:1)
像这样创建singleton
: -
class A {
static let a = A()
}
您可以在同一个多个类中访问上述对象 实例
class B {
func someMethod() {
let a = A.a
}
}
class C {
func someMethod() {
let a = A.a
}
}